gpt4 book ai didi

java - 如何重构/聚合 Java 中 ArrayList 中的数值?

转载 作者:行者123 更新时间:2023-12-03 23:00:42 25 4
gpt4 key购买 nike

我有一个如下所示的 POJO:

public class AgentSales {
private String agent;
private int month;
private int year;
private int salesCount;

public AgentSales(String agent, int month, int year, int salesCount) {
// initializers ...
}

// getters & setters
// ...
}

还有一个像下面这样的集合:

ArrayList<AgentSales> salesList = new ArrayList<AgentSales>();

salesList.add(new AgentSales("Ben", 1, 2013, 3));
salesList.add(new AgentSales("Ben", 1, 2013, 2));
salesList.add(new AgentSales("Ben", 2, 2013, 1));
salesList.add(new AgentSales("Ben", 3, 2013, 1));
salesList.add(new AgentSales("Ben", 2, 2013, 2));
salesList.add(new AgentSales("Tim", 1, 2013, 1));
salesList.add(new AgentSales("Tim", 1, 2013, 1));
salesList.add(new AgentSales("Tim", 2, 2013, 1));
salesList.add(new AgentSales("Tim", 4, 2013, 1));
salesList.add(new AgentSales("Tim", 2, 2013, 5));
salesList.add(new AgentSales("Joe", 2, 2013, 1));
salesList.add(new AgentSales("Joe", 2, 2013, 2));
salesList.add(new AgentSales("Joe", 3, 2013, 1));
salesList.add(new AgentSales("Joe", 3, 2013, 2));
salesList.add(new AgentSales("Joe", 3, 2013, 1));

如何重构/聚合这个 ArrayList 的内容,以便将对应于同一月份和代理的多个项目合并为 1,并将 salesCount 值相加?

Agent | month | year | sales count
----------------------------------
Ben | 1 | 2013 | 5
Ben | 2 | 2013 | 3
Ben | 3 | 2013 | 1
Tim | 1 | 2013 | 2
Tim | 2 | 2013 | 6

最佳答案

使用 HashMap<String,AgentSales>其中key为agent+month+year进行聚合。

有点像这样:

HashMap<String,AgentSales> aggregate = new HashMap<>();
for (AgentSales as : salesList) {
String key = as.getAgent() + as.getMonth() + as.getYear();
AgentSales existing = aggregate.get(key);
if (existing==null) {
aggregate.put(key,as);
continue;
}
AgentSales combined = new AgentSales(as.getAgent(), as.getMonth(), as.getYear(), as.getSalesCount()+exisgint.getSalesCount());
aggregate.put(key, combined);
}

现在您在 map 中有了按代理人+月份+年份的组合值。然后你可以像这样将它们作为 ArrayList 取回:

ArrayList<AgentSales> asList = new ArrayList<>(aggregate.values());

然后您可以对其进行排序(通过编写 Comparator<AgentSales> 或让 AgentSales 实现 Comparable<AgentSales> )并打印出来

关于java - 如何重构/聚合 Java 中 ArrayList 中的数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18469245/

25 4 0