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

16

我需要将数组列表中相同的值分开并计数,然后根据出现次数打印它们。

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

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

我创建了一个方法,它可以将每个值分离并保存到一个新的数组中。

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;

}

在这之后,我得到了一个名为 numbers 的新数组。我正在对这个数组使用排序功能(sort)。


Collections.sort(numbers);

我的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]

它有:

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;

根据数字的数量,我需要打印出数字字符串。应该像这样: 1354678290


那么,如果你已经有了数字数组,你卡在哪里了? - RealSkeptic
13个回答

22
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");

12

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


2
今天我才知道这个存在。我差点写了一个非常长的答案哈哈。不错! - ArsenArsen
3
它计算特定项出现的次数。它不会创建频率表,也不会按任何特定顺序排序。这意味着在此和正确答案之间仍有很长的路要走。 - RealSkeptic

10

这个问题是要在一个数组中计算有多少个1、2和3。 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

}}

在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 )                    );

}}

另一种方法是使用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));
    }

}}

另一种方法是使用方法=> Arrays.stream(array).boxed().collect(Collectors.toList()) 将int数组转换为Integer列表,然后使用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
}

7

好的,对于这个问题,您可以尝试使用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);
  }

在forEach循环结束后,您将拥有一个填充了您的物品以及它们的计数的映射表。


7
例如,通过使用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));
    }
}

3

您可以通过将列表中的所有元素相加并将其存储在哈希集中来计算重复元素的数量,完成此操作后,您只需要知道哈希集和列表大小之间的差异即可。

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);

如果需要更多澄清,请告诉我。


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

public class A_List_Find_Duplicate_Count {

    public static void main(String[] args) {
        
        List<String> list = Arrays.asList(
                "Chennai","Bangalore","Pune","Hyderabad",
                "Chennai","Pune","Mysore","Delhi","Hyderabad",
                "Pune"
                );
        String elementToFound = "Chennai";
        
        //JAVA 8 
        long count = list.stream().filter(i->elementToFound.equals(i)).count();
        System.out.println("elementToFound : "+count);
        
        
        //using Collections
        int frequency = Collections.frequency(list, elementToFound);
        System.out.println("frequency : "+frequency);
        
        
        //using Map
        HashMap<String, Integer> map = new HashMap<>();
        for(String s : list)
        {
            map.put(s, map.get(s)!=null ? map.get(s)+1 : 1);
        }
        
        System.out.println("map : "+map.get(elementToFound));
        
        //JAVA 8 using groupingBy
        Map<String, Long> collect = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        System.out.println("collect groupingBy : "+collect.get(elementToFound));
        

    }

}

输出

要查找的元素:2 频率:2 映射:2 收集分组:2


0

通用算法

定义一个空元素类型的集合,计数器int变量对=0。

  1. 使用for循环开始迭代
  2. 检查元素是否存在于集合中
    • 如果不存在,则将元素添加到集合中并移到下一次迭代
    • 如果存在,则从集合中删除元素,并将配对计数器增加1`

// public static int findDuplicate(int n, List ar) {

int pairs=0;
  Set<Integer> color=new HashSet<Integer>();
  for(int i=0;i<ar.size();i++)
  {
      if(color.contains(ar.get(i)))
      {
      pairs++;
      color.remove(ar.get(i));
      }
      else{
          color.add(ar.get(i));  
      }
  }
  return pairs;
}

} //


0
public void printCountNumber(List<Integer> numberList) {
    for(int number:numberList.stream().distinct().collect(Collectors.toList())) {
        System.out.println(number +" Times "+Collections.frequency(numberList, number));            
    }
}

Java 8 - 如何在流或列表中查找重复项


0

Java 8可以用三行代码解决这个问题。

    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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接