Java 如何计算ArrayList中的重复元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44367203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:30:50  来源:igfitidea点击:

How to count duplicate elements in ArrayList?

javasortingarraylist

提问by Piotr Szczepanik

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

我需要分离并计算arraylist中有多少个值是相同的,并根据出现的次数打印它们。

I've got an arraylist called digits :

我有一个名为 numbers 的数组列表:

 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]

I created a method which separates each value and saves it to a new array.

我创建了一个方法来分隔每个值并将其保存到一个新数组中。

public static ArrayList<Integer> myNumbers(int z) {

    ArrayList<Integer> digits = new ArrayList<Integer>();
    String number = String.valueOf(z);
    for (int a = 0; a < number.length(); a++) {
        int j = Character.digit(number.charAt(a), 10);
        digits.add(j);
    }
    return digits;

}

After this I've got a new array called numbers. I'm using sort on this array

在此之后,我有了一个名为 numbers 的新数组。我在这个数组上使用排序

Collections.sort(numbers);

and my ArrayList looks like this:

我的 ArrayList 看起来像这样:

[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9]

It has:

它有:

2 times 0; 
9 times 1;
4 times 2;
6 times 3;
5 times 4;
6 times 5;
5 times 6;
5 times 7;
5 times 8;
3 times 9;

I need to print out the string of numbers depend on how many are they So it suppose to look like this : 1354678290

我需要打印出一串数字取决于它们有多少所以它看起来像这样:1354678290

采纳答案by pruthwiraj.kadam

List<String> list = new ArrayList<String>();
    list.add("a");
    list.add("b");
    list.add("c");
    list.add("a");
    list.add("a");
    list.add("a");

int countA=Collections.frequency(list, "a");
int countB=Collections.frequency(list, "b");
int countC=Collections.frequency(list, "c");

回答by PrabaharanKathiresan

use Collections.frequency method to count the duplicates

使用 Collections.frequency 方法计算重复项

回答by Andrew Petryk

Well, for that you can try to use Map

好吧,为此你可以尝试使用 Map

Map<Integer, Integer> countMap = new HashMap<>();

  for (Integer item: yourArrayList) {

      if (countMap.containsKey(item))
          countMap.put(item, countMap.get(item) + 1);
      else
          countMap.put(item, 1);
  }

After end of forEach loop you will have a filled map with your items against it count

在 forEach 循环结束后,您将有一个填充的地图,其中包含您的项目计数

回答by Florian Salihovic

By using the Stream API for example.

例如,通过使用 Stream API。

package tests;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Duplicates {

    @Test
    public void duplicates() throws Exception {
        List<Integer> items = Arrays.asList(1, 1, 2, 2, 2, 2);

        Map<Integer, Long> result = items.stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        Assert.assertEquals(Long.valueOf(2), result.get(1));
        Assert.assertEquals(Long.valueOf(4), result.get(2));
    }
}

回答by Srivastava

You can count the number of duplicate elements in a list by adding all the elements of the list and storing it in a hashset, once that is done, all you need to know is get the difference in the size of the hashset and the list.

您可以通过添加列表的所有元素并将其存储在哈希集中来计算列表中重复元素的数量,一旦完成,您需要知道的就是获取哈希集和列表的大小差异。

ArrayList<String> al = new ArrayList<String>();
al.add("Santosh");
al.add("Saket");
al.add("Saket");
al.add("Shyam");
al.add("Santosh");
al.add("Shyam");
al.add("Santosh");
al.add("Santosh");
HashSet<String> hs = new HashSet<String>();
hs.addAll(al);
int totalDuplicates =al.size() - hs.size();
System.out.println(totalDuplicates);

Let me know if this needs more clarification

让我知道这是否需要更多说明

回答by Soudipta Dutta

The question is to count how many ones twos and threes are there in an array. In Java 7 solution is:

问题是计算数组中有多少个三三两两。在 Java 7 中,解决方案是:

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class howMany1 {
public static void main(String[] args) {

    List<Integer> list = Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765);

    Map<Integer ,Integer> map = new HashMap<>();

      for(  Integer r  : list) {
          if(  map.containsKey(r)   ) {
                 map.put(r, map.get(r) + 1);
          }//if
          else {
              map.put(r, 1);
          }
      }//for

      //iterate

      Set< Map.Entry<Integer ,Integer> > entrySet = map.entrySet();
      for(    Map.Entry<Integer ,Integer>  entry : entrySet     ) {
          System.out.printf(   "%s : %d %n "    , entry.getKey(),entry.getValue()  );
      }//for

}}

In Java 8, the solution to the problem is :

在 Java 8 中,问题的解决方案是:

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class howMany2 {
public static void main(String[] args) {

    List<Integer> list = Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765);
     // we can also use Function.identity() instead of c->c
    Map<Integer ,Long > map = list.stream()
            .collect(  Collectors.groupingBy(c ->c , Collectors.counting())         ) ;


    map.forEach(   (k , v ) -> System.out.println( k + " : "+ v )                    );

}}

One another method is to use Collections.frequency. The solution is:

另一种方法是使用 Collections.frequency。解决办法是:

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Duplicates1 {
public static void main(String[] args) {

    List<Integer> list = Arrays.asList(1, 1, 2, 3, 5, 8, 13,13, 21, 34, 55, 89, 144, 233);

    System.out.println("Count all with frequency");
    Set<Integer> set = new HashSet<Integer>(list);
    for (Integer r : set) {
        System.out.println(r + ": " + Collections.frequency(list, r));
    }

}}

Another method is to change the int array to Integer List using method => Arrays.stream(array).boxed().collect(Collectors.toList()) and then get the integer using for loop.

另一种方法是使用 method => Arrays.stream(array).boxed().collect(Collectors.toList()) 将 int 数组更改为整数列表,然后使用 for 循环获取整数。

public class t7 {
    public static void main(String[] args) {
        int[] a = { 1, 1, 2, 3, 5, 8, 13, 13 };
        List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());

        for (Integer ch : list) {
            System.out.println(ch + " :  " + Collections.frequency(list, ch));
        }

    }// main
}

回答by Madina Mountaniol

Java 8, the solution: 1. Create Map when the Key is the Value of Array and Value is counter. 
2. Check if Map contains the Key increase counter or add a new set.

 private static void calculateDublicateValues(int[] array) {
      //key is value of array, value is counter
      Map<Integer, Integer> map = new HashMap<Integer, Integer>();

      for (Integer element : array) {
        if (map.containsKey(element)) {
          map.put(element, map.get(element) + 1); // increase counter if contains
        } else
          map.put(element, 1);
      }

      map.forEach((k, v) -> {
        if (v > 1)
          System.out.println("The element " + k + " duplicated " + v + " times");
      });

    }

回答by Ramij

Use below function for count duplicate elements :

使用以下函数计算重复元素:

public void countDuplicate(){
        try {
            Set<String> set = new HashSet<>(original_array);
            ArrayList<String> temp_array = new ArrayList<>();
            temp_array.addAll(set);
            for (int i = 0 ; i < temp_array.size() ; i++){
                Log.e(temp_array.get(i),"=>"+Collections.frequency(original_array,temp_array.get(i)));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

回答by Bhushan Uniyal

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

Java 8 可以用 3 行代码处理这个问题。

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