gpt4 book ai didi

java - 如何合并相似对象的列表,但用 Java 8 总结一些属性

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:43:17 29 4
gpt4 key购买 nike

假设我有下面的列表,我想返回一个结果,其中只有一个人的名字是 "Sam" - "Fred" 25 数量

public class Java8Test{


private static class Person {
private String name;
private String lastName;
private int amount;

public Person(String name, String lastName, int amount) {
this.name = name;
this.lastName = lastName;
this.amount = amount;
}
}


public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Sam","Fred",10));
people.add(new Person("Sam","Fred",15));
people.add(new Person("Jack","Eddie",10));
// WHAT TO DO HERE ?


}
}

注意:

上面的例子只是为了说明,我正在寻找的是一个通用的 map/reduce 类 Java 8 功能。

最佳答案

您可以迭代您的 people列出并使用 map 合并具有相同 name - lastName 的人对:

Map<String, Person> map = new HashMap<>();
people.forEach(p -> map.merge(
p.getName() + " - " + p.getLastName(), // name - lastName
new Person(p.getName(), p.getLastName, p.getAmount()), // copy the person
(o, n) -> o.setAmount(o.getAmount() + n.getAmount()))); // o=old, n=new

现在map.values()是一个减少 Collection<Person>根据您的要求。

如果您有可能向 Person 添加一个复制构造函数和几个方法类:

public Person(Person another) {
this.name = another.name;
this.lastName = another.lastName;
this.amount = another.amount;
}

public String getFullName() {
return this.name + " - " + this.lastName;
}

public Person merge(Person another) {
this.amount += another.amount;
}

然后,您可以简化第一个版本的代码,如下所示:

Map<String, Person> map = new HashMap<>();
people.forEach(p -> map.merge(p.getFullName(), new Person(p), Person::merge));

这利用了 Map.merge 方法,这对这种情况非常有用。

关于java - 如何合并相似对象的列表,但用 Java 8 总结一些属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47817633/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com