1 回答
TA贡献1789条经验 获得超8个赞
这个λ:
Map<String, List<HashMap<String, Object>>> xxx = arrList.stream().collect(Collectors.groupingBy(x -> ((int) x.get("ID") + "") + x.get("NAME")));
给出的结果如下:
但是,如上所述 - 您应该使用(如果可能)对象而不是数组。对于对象,lambda 将如下所示:
Map<String, List<Person>> xxx = arrList.stream().collect(Collectors.groupingBy(x -> x.getName() + x. getId()));
但是由于您有 Person 类,因此您可以覆盖等于以满足您的需求,并且可以在一个简单的 lambda 中映射和求和工作时间:
Map<Person, Double> result = arrList.stream().collect(Collectors.groupingBy(x -> x, Collectors.summingDouble(Person::getWorkTime)));
这就是结果 - 将人员地图作为键,将工作时间摘要作为值。
人员类的代码:
public class Person {
String name;
int id;
double workTime;
public Person(String name, int id, double workTime) {
this.name = name;
this.id = id;
this.workTime = workTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return id == person.id &&
Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, id);
}
}
示例代码:
Person person1 = new Person("Edward", 1, 20);
Person person2 = new Person("Krzych", 1, 6);
Person person3 = new Person("Edward", 1, 13.5);
Person person4 = new Person("Grzesiek", 2, 50);
Person person5 = new Person("Edward", 2, 12);
ArrayList<Person> arrList = new ArrayList<>();
arrList.add(person1);
arrList.add(person2);
arrList.add(person3);
arrList.add(person4);
arrList.add(person5);
Map<Person, Double> result = arrList.stream().collect(Collectors.groupingBy(x -> x, Collectors.summingDouble(Person::getWorkTime)));
添加回答
举报