Search code examples
javaarrayshashmap

find duplicates using HashMap


I want to find duplicated values on a String . I know there are other solutions to find that but i want to use HashMap. here is my solution.!! what i am missing on the last part ? i want to get just the duplicate letters

public static void doublicatess(String str) {
             
             HashMap <String , Integer> hashmap = new HashMap<>();
             String[] array = str.split("");
             for( String string : array) {
                 if(hashmap.get(string) == null) {
                     hashmap.put(string, 1);
                 }else {
                     hashmap.put(string, hashmap.get(string) + 1);
                 }
             }
             
             for(int i = 0 ; i < hashmap.size() ; i++) {
                 int target = hashmap.get(array[i]);
                 if(target > 1) {
                     System.out.print(hashmap.get(target));
                 }
             }
         }
public static void main(String[] args) {
        doublicatess("alaaass");
    }

the output is null while it should be [a,s]


Solution

  • You are iterating by using the hashmapsize and indexing into the array using the count which is wrong.

    Try this

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

    Using streams, you can write this in a functional/declarative way (might be advanced to you)

    Arrays.stream(array)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .entrySet()
                .stream()
                .filter(entry -> entry.getValue() > 1)
                .map(Map.Entry::getKey)
                .forEach(System.out::println);