【问题标题】:Removing duplicate elements in an ArrayList and adding the total number of occurrences in parentheses after the first element删除 ArrayList 中的重复元素并在第一个元素后的括号中添加出现的总数
【发布时间】:2012-04-06 21:48:52
【问题描述】:

这里是初学者。我有一个 String ArrayList,在打印时基本上看起来像这样(但值的变化取决于用户输入):

[22、37、77、77、98、101、104、107、107、107、150]

我想删除重复的元素,并在第一个元素之后的括号中添加出现的总次数,所以它看起来像这样:

[22, 37, 77 (2), 98, 101, 104, 107 (3), 150]

我已经弄清楚如何删除重复的元素,但我无法完全弄清楚其余的。

到目前为止,这是我的代码(ArrayList 称为重复项):

int q, z;
for(q = 0; q < duplicates.size() - 1; q++) {  
    for(z = q + 1; z < duplicates.size() - 1; z++) {
        if(duplicates.get(q).equals(duplicates.get(z))) {
            duplicates.remove(q);
        }
    }
}

System.out.println(duplicates);

结果输出是:

[22、37、77、98、101、104、107、150]

有没有人对我如何获得括号中的出现次数有任何建议?我一直在努力想出一种方法来计算每个值删除的重复项,但我所能计算的只是删除期间的重复项总数,这并不是特别有用。

ArrayList 最初是一个 Integer ArrayList,但我将其更改为 String ArrayList,以便可以将非数字字符添加到元素中。

【问题讨论】:

    标签: java arraylist duplicates


    【解决方案1】:

    我建议使用 Map。您可以使用它来将键与 有用 值相关联。在这种情况下,键是要处理的数组元素,值是数组中每个元素的出现次数。你的伪代码是:

    initialize a map of appropriate size and type
    iterate the array to be processed. for each element in array:
    
    set key:= current element in array
    set value := value from map corresponding to key
    if value is null, initialize value to 1
    store value for key in map
    

    然后在最后你将迭代 map 的键并打印出键及其对应的值。

    【讨论】:

      【解决方案2】:

      ArrayList 最初是一个 Integer ArrayList,但我将其更改为 String ArrayList,以便可以将非数字字符添加到元素中。

      这是一个错误。不要混淆您希望如何在代码中存储数据以及如何向用户显示数据。如果您将您的值存储为List 或String,那么您会让事情变得更加困难。以最容易编码的形式存储值,并且只有在您想要显示它们时才转换为字符串。

      因此,您需要的是一个唯一数字列表和每个数字的计数。 Map 将是理想的,因为它将键(在您的原因中为整数)映射到值(计数)。

      所以你需要循环你的数字,然后在Map 中计算它们。在下面的代码中,我假设 list 是 List&lt;Integer&gt;。

      Map<Integer,Integer> counts = new HashMap<Integer,Integer>();
      
      for (int number : list) {
        int count = counts.containsKey(number) ? counts.get(number) : 0;
        count += 1;
        counts.put(number,count);
      }
      

      然后您可以通过循环 Map.keySet() 或 Map.entrySet() 来构建您的输出,

      【讨论】:

        【解决方案3】:

        首先,我建议您将列表保留为整数列表。不要使用System.out.println(duplicates),而是自己做一个循环。无论如何,这真的很容易。


        计算出现次数:

        我建议您维护一个Map&lt;Integer, Integer&gt;,它将数字映射到出现次数。这可以像这样在第一遍中初始化:

        1. 对于列表中的每个元素 i       (for (int i : duplicates))
          1. 如果 i 不在地图中       (map.containsKey(i))
            1. 添加映射i -> 0        (map.put(i, 0))
          2. 增加键 i 的值     (map.put(i, map.get(i) + 1))


        打印出现次数的列表:

        您打印列表如下:

        1. 为已打印的号码创建HashSet&lt;Integer&gt; printed
        2. 对于列表中的每个元素 i
          1. 如果 i 是 printed,则执行,继续:(if (printed.contains(i)) continue;)
          2. 打印我
          3. 如果 i 的映射值 > 1,则打印括号中的数字
          4. 添加 i 以打印。 (printed.add(i))

        一旦你完成了循环练习,你就可以通过这样做来删除重复

        list = new ArrayList<Integer>(new LinkedHashSet<Integer>(list));
        

        【讨论】:

          【解决方案4】:

          声明一个ArrayList&lt;Integer&gt; 用于计数:

          ArrayList<Integer> counts = new ArrayList<Integer>();
          

          然后当您删除重复项时,增加计数

                      duplicates.remove(q);
                      counts.set(q, counts.get(q) + 1);
          

          【讨论】:

            【解决方案5】:

            LinkedHashMap 对你来说已经足够好了。 Map 接口的哈希表和链表实现,具有可预测的迭代顺序。所以,我推荐使用 LinkedHashMap 如下:

                public static LinkedHashMap<String,Integer> removeDuplicate(List<String> list)
            {
                LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
                for(String str:list)
                {
                    Integer count = map.get(str);
                    if(count == null)
                    {
                        map.put(str, 1);
                    }else{
                        map.put(str, ++count);
                    }
                }
                return map;
            }
            
            public static void main(String[] args)
            {
                List<String> list = new ArrayList<String>();
                list.add("123");
                list.add("45");
                list.add("678");
                list.add("123");
                System.out.println(removeDuplicate(list));
            }
            

            【讨论】:

              【解决方案6】:

              这里是完整的代码:

              public static void main(String[] args) {
                  /* Make list */
                  List<String> input = new ArrayList<String>();
                  input.add("12");
                  input.add("11");
                  input.add("11");
                  input.add("12");
                  input.add("12");
                  input.add("15");
                  input.add("12");
                  input.add("17");
                  input.add("18");
                  input.add("11");
              
                  /*
                   * count duplicates
                   */
                  Map<String, Integer> map = new LinkedHashMap<String, Integer>();
                  for (String str : input) {
                      if (map.containsKey(str)) {
                          Integer prevCount = map.get(str);
                          map.put(str, ++prevCount);
                      } else {
                          map.put(str, 0);
                      }
                  }
              
                  /*
                   * make string to display
                   */
                  StringBuffer sb = new StringBuffer();
                  for (Map.Entry<String, Integer> entry : map.entrySet()) {
              
                      String key = entry.getKey();
                      Integer count = entry.getValue();
                      if (count == 0) {
                          sb.append(key + ", ");
                      } else
                          sb.append(key + "(" + count + "), ");
                  }
                  String tmp = sb.toString();
                  String output = tmp.substring(0, tmp.length() - 2); //remove last ", "
                  System.out.println("[" + output + "]");
              
              }
              

              【讨论】:

              • A) 你做了这些家伙的作业(不是很有帮助) B) 你搞乱了列表中的顺序。 (甚至不是正确的解决方案)C)似乎在空列表上严重中断。
              • A) 感谢您的建议。 B)我更正了代码 - 使用了 LinkedHashMap。 C) 让jta1991把所有的case都检查一遍,让他的功课完美,不是很好吗?
              【解决方案7】:

              在谷歌图书馆Guava 的帮助下(恕我直言,非常有用)你可以这样写:

              List<String> duplicate = ImmutableList.of("22", "37", "77", "77", "98", "101", "104", "107", "107", "107", "150");
              
              System.out.println(duplicate); 
              
              Multiset<String> withoutDuplicate = LinkedHashMultiset.create();
              withoutDuplicate.addAll(duplicate);
              
              System.out.println(withoutDuplicate); 
              

              这会产生

              [22, 37, 77, 77, 98, 101, 104, 107, 107, 107, 150]
              [22, 37, 77 x 2, 98, 101, 104, 107 x 3, 150]
              

              这不完全是你的格式,但它是一个两行。

              【讨论】:

                【解决方案8】:
                List<Integer> completeList = new ArrayList<Integer>();
                completeList.add(22);
                completeList.add(22);
                completeList.add(37);
                completeList.add(77);
                completeList.add(77);
                completeList.add(98);
                completeList.add(101);
                completeList.add(107);
                completeList.add(107);
                completeList.add(107);
                completeList.add(150);
                
                System.out.println(completeList);
                
                // Using a sortedSet to remove the duplicates
                SortedSet<Integer> nonDupSet = new TreeSet<Integer>(completeList);
                System.out.println(nonDupSet);
                
                List<String> datawithParan = new ArrayList<String>();
                //Looping through the completeList with the nonDup List and counting the dups.
                // and then populating a List with the required Format
                for (Integer nonDup: nonDupSet) {
                    int count = 0;
                    for (Integer complete: completeList) {                      
                      if(nonDup == complete) {
                        count++;
                      }
                    }
                
                    datawithParan.add(nonDup +"(" + count + ")");
                }
                System.out.println(datawithParan);
                

                【讨论】:

                  猜你喜欢
                  • 2012-10-10
                  • 1970-01-01
                  • 2015-07-20
                  • 2017-11-17
                  • 2012-12-02
                  • 2014-05-06
                  • 1970-01-01
                  • 2019-07-10
                  • 1970-01-01
                  相关资源
                  最近更新 更多