【问题标题】:Find the duplicate elements in arraylist and display [closed]在arraylist中查找重复元素并显示[关闭]
【发布时间】:2012-10-18 05:49:26
【问题描述】:

有人可以帮我吗?我需要编写一个程序,其中 arraylist 中有 10 个元素,我需要找到它有多少重复值,并计算和显示这些值。

例如:说我有

list = {"stack", "overflow", "stack", 
        "yahoo", "google", "msn", 
        "MSN", "stack", "overflow", "user" }

结果应该是:

stack = 3
overflow = 2
google = 1
msn = 2
yahoo =1
user = 1

【问题讨论】:

  • 请提供一个示例,说明您在 SO 上发布之前尝试过的操作。

标签: java collections arraylist


【解决方案1】:

使用 HashMap。这是一个简单的实现

List<String> strings = new ArrayList<String>();
strings.put("stack", "overflow", "stack", "yahoo", "google", "msn", "MSN", "stack", "overflow", "user");

Map<String, Integer> counts = new HashMap<String, Integer>();

for (String str : strings) {
    if (counts.containsKey(str)) {
        counts.put(str, counts.get(str) + 1);
    } else {
        counts.put(str, 1);
    }
}

for (Map.Entry<String, Integer> entry : counts.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

【讨论】:

  • 简单,感谢您的帮助:)
【解决方案2】:

使用 Google Guava 库的 MultiSet。它支持添加多个元素,并计算多重集包含的每个元素的出现次数。

Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(words);
for(Multiset.Entry<String> entry : wordsMultiset.entrySet() ){
     System.out.println("Word : "+entry.getElement()+" count -> "+entry.getCount());
}

【讨论】:

  • 是的 - 比使用 HashMap 的所有建议简单得多...
【解决方案3】:

使用hashmap
像这样:

Map<String, Integer> occurrencies = new HashMap<String, Integer>();
for (String word : list) {
    occurrencies.put(word, occurrencies.containsKey(word)
    ? occurrencies.get(word) + 1 : 1);
}
for (Entry<String, Integer> entry : occurrencies.entrySet()) {
    System.out.println("Word: "+entry.getKey()
                     + ", occurences: "+entry.getValue());
}

【讨论】:

    【解决方案4】:
    Map<String, Integer> frequency = new HashMap<String, Integer>();
    for (String element : list) {
        if (frequency.contains(element)) {
            frequency.put(element, frequency.get(element) + 1);
        }
        else {
            frequency.put(element, 1);
        }
    }
    for (Map.Entry<String, Integer> entry : frequency.entrySet()) {
        System.out.print(entry.getKey() + " = " + entry.getValue() + " ");
    }
    System.out.println();
    

    【讨论】:

      【解决方案5】:

      使用HashMap

      Map<String, Integer> freqMap = new HashMap<String, Integer>();
      

      【讨论】:

        【解决方案6】:

        创建一个Map&lt;String, Integer&gt;,然后遍历您的ArrayList

        那么对于每个元素:-

        • 如果它已经存在于 Map 中,则将该元素的 Integer 值增加 1
        • 如果不存在,则添加具有initial Integer 值为1 的元素

        【讨论】:

          猜你喜欢
          • 2016-10-05
          • 1970-01-01
          • 2022-01-18
          • 2011-11-02
          • 2015-08-08
          • 1970-01-01
          • 2013-06-20
          • 2019-09-30
          相关资源
          最近更新 更多