How to count duplicate elements in ArrayList?

前端 未结 10 1563
悲哀的现实
悲哀的现实 2020-12-15 11:55

I need to separate and count how many values in arraylist are the same and print them according to the number of occurrences.

I\'ve got an arraylist called digits :<

10条回答
  •  离开以前
    2020-12-15 12:07

    Java 8 can handle this problem with 3 lines of code.

        Map  duplicatedCount = new LinkedHashMap<>();
        list.forEach(a -> duplicatedCount.put(a, duplicatedCount.getOrDefault(a, 0) +1));
        duplicatedCount.forEach((k,v) -> System.out.println(v+" times "+k));
    

提交回复
热议问题