How to find duplicate rows and display the number of repetitions in front of them

  • A+
Category:Languages

Yes, a trivial question, but I did not find a duplicate. At the moment, from this collection (ArrayList):

Java C# Java Python 

I must get this: (That is, over each word will be the number of duplicates encountered)

Java 2 C# 1 Java 2 Python 1 

At the moment I'm using Map, but it removes duplicates and that's what I get.

Java 2 C# 1 Python 1 

Here is my code:

      Map<String, Integer> map = new HashMap<>();         for (String temp : array) {             Integer count = map.get(temp);             if (count != null){                 map.put(temp, count + 1);             }             else {                 map.put(temp, 1);             }         } 

I had an idea to write data to another list, to go through this list comparing each element of the "parent" list with all the elements of the new list. Something like that:

List<String> resultList = new ArrayList<>(); List<String> mainList = new ArrayList<>();      for (int i = 0; i < arrayList.size(); i++) {         mainList.add(i,arrayList.get(i));     }      for (int i = 0; i < mainList.size(); i++) {             int x = 1;         for (String anArray : arrayList) {             if (mainList.get(i).equals(anArray)) {                 resultList.add(i,mainList.get(i) + " "+ x++);             }         }     }     resultList.forEach(System.out::println); 

Which works as I need, but also creates an additional line when it encounters a duplicate.

Java 2 C# 1 Java 2 Python 1 Java 1 Java 1 

In the implementation with List, I have a problem in that it increases the current element by 1, but also creates another one at the same time.

Guys, I'll be happy with any idea or clue that will guide me to solving my problem!

UPD: All answers to this question are divine. Thank you guys! I feel awkward trying to choose the right answer without offending others.

 


You can use Collections.frequency while iterating the list to print the number of occurrences of each word in the list:

public static void main(String[] args) {     List<String> list = Arrays.asList("Java", "C#", "Java", "Python");     list.forEach( s -> System.out.println(s + " " + Collections.frequency(list, s))); } 

Output:

Java 2 C# 1 Java 2 Python 1 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: