java program to print unique characters in a sentence code example

Example 1: find unique characters in java

//  I would use linkedHashMap since it doesn't accept
//  duplicate values

String str = "abbcdddefffggghjilll";
        String [] arr = str.split("");
        Map<String, Integer> mapStr = new LinkedHashMap<>();

        for (int i=0 ; i < arr.length ; i++){
            if (!mapStr.containsKey(arr[i])){
                mapStr.put(arr[i],1);
            } else{
                mapStr.put(arr[i],mapStr.get(arr[i])+1);
            }
        }

        for (Map.Entry<String,Integer> map : mapStr.entrySet()) {
            if(map.getValue()==1) {
                System.out.print(map.getKey());
            }
        }

Example 2: java program to print unique words in a sentence

import java.util.Arrays;
import java.util.HashSet;
 
/**
 * Java Program - Find Unique Words
 */
public class Example {
 
    public static void main(String[] args) {
 
        String str = "apple banana mango grape lichi mango apple grape";
         
        String[] words = str.split(" ");
         
        HashSet<String> uniqueWords = new HashSet<String>(Arrays.asList(words));
         
        for(String s:uniqueWords)
            int i=1;
            System.out.println(i+". "+s);
    }
 
}

Tags:

Java Example