【问题标题】:How to count duplicate elements in ArrayList?如何计算 ArrayList 中的重复元素?
【发布时间】:2017-11-06 02:59:03
【问题描述】:

我需要将arraylist中有多少个相同的值分开计算,并根据出现的次数打印出来。

我有一个名为 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 的新数组。我在这个数组上使用排序

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

【问题讨论】:

  • 那么,如果你已经有了数字数组,你会卡在哪里?

标签: java sorting arraylist


【解决方案1】:
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");

【讨论】:

    【解决方案2】:

    问题是计算一个数组中有多少个二和三。 在 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 List,然后使用 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
    }
    

    【讨论】:

      【解决方案3】:

      使用Collections.frequency方法计算重复次数

      【讨论】:

      • TIL 存在。我正要写一个很长的答案哈哈。不错的一个
      • 它计算特定项目的出现次数。它不会创建频率表,也不会按任何特定顺序对它们进行排序。这意味着这与正确答案之间还有很长的路要走。
      【解决方案4】:

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

      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 循环结束后,您将拥有一个填充地图,其中包含您的项目计数

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

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

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

          如果需要进一步说明,请告诉我

          【讨论】:

            【解决方案7】:
            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));
                    
            
                }
            
            }
            

            输出

            elementToFound : 2 频率 : 2 地图 : 2 收集 groupingBy : 2

            【讨论】:

              【解决方案8】:
              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");
                    });
              
                  }
              

              【讨论】:

              • 一团代码并不总是最好的答案。你能edit这个答案并提供一些背景或解释你认为这如何回答这个问题吗?此外,格式已损坏。
              【解决方案9】:

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

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

              【讨论】:

                【解决方案10】:

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

                【讨论】:

                  【解决方案11】:

                  Map#merge方法也可以使用:

                   List<Integer> input = Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584,
                              4181, 6765);
                   final Map<Integer, Integer> result = new HashMap<>();
                   input.forEach(in -> result.merge(in, 1, Integer::sum));
                  

                  【讨论】:

                    猜你喜欢
                    • 2016-08-30
                    • 2016-03-07
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2021-04-07
                    • 2014-04-08
                    • 1970-01-01
                    • 2010-10-08
                    相关资源
                    最近更新 更多