Printing duplicate lines 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 the duplicates after iterating through my ArrayList (it was created beforehand and it just reads the given file and sorts the lines alphabetically). At the moment it prints duplicates like this:

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

etc .. Is there a way to print it in pairs (key = value \ n key = value, etc.) and without actually mentioning 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, but I couldn't think of a good way to write it.

+3


source to share


2 answers


You can also use removeIf()

(added in JDK1.8) in entrySet()

to remove words occurring only once, like 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 an Iterator to safely remove words that occurred only once, as shown in the image 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);

      

+4


source


Filter recordset to remove items with value 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);

      

+5


source







All Articles