【问题标题】:How to find the most common element(s) using Map (or Set ? ) in Java? [duplicate]如何在 Java 中使用 Map (或 Set ?)找到最常见的元素? [复制]
【发布时间】:2017-06-30 08:56:50
【问题描述】:

我在 ArrayList 中有名称,我想以最简单的方式找到最常见的元素。我尝试使用 Collectoins.max() ,但它的返回值不正确。

我创建了一个 HashMap,使用名称 az 键和名称数量作为值,但我不知道如何编写具有最高值的名称。

(实际上,如果有两个或多个值最高的名字,我必须得到它们。)

【问题讨论】:

  • 也许我们在这里谈论 Collections.frequency(Collection> c, Object o)?最常见的元素与 frequency 而不是 max?? 密切相关

标签: java dictionary arraylist


【解决方案1】:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

公共类 StringChecker {

public static void main(String[] args) {
    ArrayList<String> string;
    string = new ArrayList<>(Arrays.asList("Mah", "Bob", "mah", "bat", "MAh", "BOb"));
    Map<String, Integer> wordMap = new HashMap<String, Integer>();

    for (String st : string) {
        String input = st.toUpperCase();
        if (wordMap.get(input) != null) {
            Integer count = wordMap.get(input) + 1;
            wordMap.put(input, count);
        } else {
            wordMap.put(input, 1);
        }
    }
    System.out.println(wordMap);
    Object maxEntry = Collections.max(wordMap.entrySet(), Map.Entry.comparingByValue()).getKey();
    System.out.println("maxEntry = " + maxEntry);
}

}

【讨论】:

    猜你喜欢
    • 2011-04-05
    • 2013-11-13
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多