【发布时间】:2021-06-19 00:52:54
【问题描述】:
我有一个 Country 类,并从 .csv 文件中读取数据,该文件包含许多国家名称、它们所在的地区、每个国家的人口、地区等,并将其存储在 ArrayList 中。我主要使用 java 集合框架进行数据分析,并希望找到每个区域的 total 和 平均人口。
我认为使用 HashMap 是最好的,但我不知道该怎么做,因为我以前从未以任何复杂的方式或对象使用过。我也知道我必须将 int 的数据类型更改为 long 以用于总人口。
public class Country {
private String name;
private String region;
private int population;
private int area;
private double density;
/**
* Default constructor
*/
public Country() {
}
/**
* Creates a country with all args
*
* @param name
* @param region
* @param population
* @param area
* @param density
*/
public Country(String name, String region, int population, int area, double density) {
super();
this.name = name;
this.region = region;
this.population = population;
this.area = area;
this.density = density;
}
/**
* @return the region
*/
public String getRegion() {
return region;
}
/**
* @param region the region to set
*/
public void setRegion(String region) {
this.region = region;
}
/**
* @return the population
*/
public int getPopulation() {
return population;
}
/**
* @param population the population to set
*/
public void setPopulation(int population) {
this.population = population;
}
public static void totalPopulationByRegion(Collection<Country> countries) {
Map<String, Integer> map = new HashMap<String, Integer>();
int total = 0;
for (Country country : countries) {
if (map.containsKey(country.getRegion())) {
map.put(country.getRegion(), total);
total+=country.getPopulation();
} else
map.put(country.getRegion(), total);
}
for (Map.Entry m : map.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
从我在控制台上得到的输出中,我意识到我的数学逻辑在这方面完全是错误的,即使考虑到我没有处理过大而无法存储为 int 的数字这一事实。我没有得到我想要的键的重复项,我只是不知道如何获得映射到每个区域的人口的累积总数。对此的任何帮助将不胜感激。
从 main 方法调用时得到的输出:
Near east 41843152
Asia -478957430
Europe -7912568
Africa 54079957
Latin amer. & carib 17926472
Northern america -35219702
Baltics -1102504495
Oceania -616300040
来自 csv 文件的样本:
Country,Region,Population,Area (sq. mi.)
Afghanistan,ASIA,31056997,647500
Albania,EASTERN EUROPE ,3581655,28748
Algeria ,NORTHERN AFRICA ,32930091,2381740
American Samoa ,OCEANIA ,57794,199
Andorra ,WESTERN EUROPE ,71201,468
Angola ,SUB-SAHARAN AFRICA ,12127071,1246700
Anguilla ,LATIN AMER. & CARIB ,13477,102
Antigua & Barbuda ,LATIN AMER. & CARIB ,69108,443
Argentina ,LATIN AMER. & CARIB ,39921833,2766890
【问题讨论】:
-
你必须把计算出来的
total放回Map(Integer是不可变的)。另外我建议看一下IntSummaryStatistics或LongSummaryStatistics(如果在地图中使用而不是Integer,则无需写回) -
你认为你的
else块有什么作用?你为什么写那段代码? -
你的预期结果是什么?
-
请分享您的 Country 类、您的 csv 文件的示例输入和预期输出。
-
如果每个
Country都属于一个Region,您可以创建一个Map<Region, List<Country>>并对其进行迭代。
标签: java foreach collections hashmap data-analysis