Kirill
Kirill

Reputation: 73

Printing out string duplicates with HashMap in Java

I have this code:

HashMap<String, Integer> dupeMap = new HashMap<>();
                for (String name : sortWords)
                    if(dupeMap.containsKey(name)) {
                        int count = dupeMap.get(name);
                        dupeMap.put(name, ++count);
                    } else {
                        dupeMap.put(name, 1);
                    }

                System.out.printf("Duplicates: %s\n", dupeMap.entrySet());

I want it to print out duplicates after iterating through my ArrayList (it's been created beforehand and it just reads the given file and sorts the strings in alphabetic order). As of now it prints out duplicates this way:

Duplicates: [Eight=1, Two=2, Seven=2, Four=1]

etc. Is there a way to print it out in pairs (key=value\n key=value etc) and without actually mentioning the unique words?

I'm very new to Maps, so even for this piece of code I had to search stackoverflow, although I had the same idea in my mind, just couldn't come up with a good way to write it.

Upvotes: 3

Views: 1122

Answers (2)

Vasu
Vasu

Reputation: 22422

You can also use removeIf() (added in JDK1.8) on the entrySet() to remove the words occured only once as shown below:

Set<Map.Entry<String, Integer>> elements = dupeMap.entrySet();
elements.removeIf(element->element.getValue() ==1);//removes words ocured only once
System.out.printf("Duplicates: %s\n",elements);

OUTPUT:

Duplicates: [Two=2, Seven=2]

If you are using JDK1.7 or earlier, you need to use Iterator to safely remove the words occured only once as shown below:

Set<Map.Entry<String, Integer>> elements = dupeMap.entrySet();
Iterator<Map.Entry<String, Integer>> iterator = elements.iterator();
while(iterator.hasNext()) {
   Map.Entry<String, Integer> element = iterator.next();
   if(element.getValue() ==1) {
       iterator.remove();
    }
}
System.out.printf("Duplicatesss: %s\n",elements);

Upvotes: 4

Andy Turner
Andy Turner

Reputation: 140318

Filter the entry set to remove elements with a value of 1:

List<Map.Entry<String, Integer>> dupes = dupeMap.entrySet()
    .stream()
    .filter(e -> e.getValue() > 1)
    .collect(Collectors.toList());

Then:

System.out.printf("Duplicates: %s\n", dupes);

Upvotes: 5

Related Questions