find unique from a string in java 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());
            }
        }

Example 3: find unique from a string in java

public class String_FindtheUnique_4 {
/* Write a return  method that can find the unique characters from the String
 Ex:  unique("AAABBBCCCDEF")  ==>  "DEF";  */
    public static void main(String[] args) {

   String result1 = Unique("BBCCDDSSEEDDYUT");
   System.out.println(result1); // YUT

//1.yol 
    String s = "BABABACDR";
    String r = "";
    for(String each : s.split(""))
 r += ( (Collections.frequency(Arrays.asList(s.split("")), each)) ==1 ) ? each : "";
     System.out.println(r); // CDR
    }

//2.yol method yolu
  public static String Unique(String str) {
        String result1 ="";
        for(String each : str.split(""))
result1 += ( (Collections.frequency(Arrays.asList(str.split("")), each)) ==1 ) ? each : "";
        return result1;
    }

}

Tags:

Cpp Example