你如何在对象中创建一个方法来使用 hashmap 找到最大的数字?

How do you create a method in objects that finds the highest number using hashmap?

我是 hashmap 的新手,我正在尝试使用 hashmap 找到人口最多的大陆,但我不知道从这里到哪里去。

这些是我的字段,我想把大陆放在关键部分,人口放在价值部分

private String name;
private int population;
private double area;
private String continent;

这是我创建该方法的尝试,但它不完整。

public void findMostPopulousContinent() {
    /* Hashmap<Key, Value> */
    HashMap<String, Integer> dummy = new HashMap<String, Integer>();

    for (int i = 0; i < size; i++) {
        if (dummy.containsKey(catalogue[i].getContinent())) {
            Integer pop = dummy.get(catalogue[i].getContinent());
            pop = pop + catalogue[i].getPopulation();


        }
        else {
            dummy.put(catalogue[i].getContinent(), catalogue[i].getPopulation());
        }
    }
}

我想要发生的是将我的实例放入哈希图中,如果我的实例具有相同的大陆,则添加它们的人口,然后将其与其他大陆进行比较,然后打印人口最多的大陆,例如

North America, 100000000

您需要汇总人口,您可以使用地图的merge()方法。

但您不需要所有这些代码:

鉴于:

record Country(String continent, Integer population) {}
Country[] catalog;

然后:

Map<String, Integer> continentPopulations = Arrays.stream(catalog)
    .collect(groupingBy(Country::continent, summingInt(Country::population)));

秘诀是使用 groupingBy(classifier, downstream) 收集器:

groupingBy(Country::continent, summingInt(Country::population))

要获得人口最多的大陆,您可以跳过对地图的引用并使用流为您找到基于人口的最大值:

String mostPopulousContinentName = Arrays.stream(catalog)
    .collect(groupingBy(Country::continent, summingInt(Country::population)))
    .entrySet().stream()
    .max(Map.Entry.comparingByValue())
    .get().getKey();