Java – how to find duplicate rows and display the number of repetitions before them

Yes, it's a trivial problem, but I didn't find a duplicate problem Currently, from this collection (ArrayList):

Java
C#
Java
Python

I have to get this: (that is, each word will encounter the number of repetitions)

Java 2
C# 1
Java 2
Python 1

I'm currently using map, but it will delete duplicates. That's what I get

Java 2
C# 1
Python 1

This 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 have an idea to write data to another list and compare each element of the "parent" list with all elements of the new list Something like this:

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, but an additional row is created in case of duplication

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

In the implementation using list, the problem I encountered was that it increased the current element by 1, but created another element at the same time

Guys, I'll be happy to lead me to any ideas or clues to solve the problem!

UPD: all the answers to this question are sacred Thank you! Without offending others, I think it's embarrassing to choose the right answer

Solution

You can use collections when iterating over a list Frequency 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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>