java find distinct characters in a string code example

Example 1: how to find unique characters in a string 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: 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());
            }
        }

Tags:

Cpp Example