Home > Enterprise >  How to find the duplicates using Streams in java for below input
How to find the duplicates using Streams in java for below input

Time:08-25

How to use Streams in java for below input.

    **INPUT:**
    Map<Integer,String> res1 = new HashMap<>();
    res1.put(1, "NaaveeKKn");
    res1.put(2, "lavanayana");

   **EXPECTED OUTPUT**
   [[a,e,K],[a,n]]

CodePudding user response:

  1. Create a Map<Character,Boolean> where the character is your character you traverse. As you traverse, if it is not in the map, put it in as the key with value False. If it is in the map, set the value to True. Then for each input string do this with a map.
  2. If you are limited to the normal ASCII/UTF characters (letters), create an array of integers say of size 256. As you traverse the string, use each character's numeric value as the index the array and the value at the array index. Then just print the characters that are the character conversion of the numeric index and only print the ones with values more than 1. Same deal hear, do this for each input string.
  3. If you need to preserve order you could also do something like #1 or #2 and traverse the original string only echoing the characters for the "True" in the Map case or "greater than 1" in the array case by using the data structures from #1 or #2.

CodePudding user response:

You can use nice feature provided by Set collection. When you call set.add(smthng) it returns you boolean values. True means that object is not present in the set and it will be added into it, False means that such object is already in the set.

So you can transform you string to char stream and filter base on value returned by add method

private Character[] findDuplicates(String str) {
    Set<Character> chars = new HashSet<>();
   return str.chars()
           .mapToObj(c -> (char) c)
           .filter(c -> !chars.add(c))
           .toArray(Character[]::new);
}
  •  Tags:  
  • java
  • Related