我有一个包含成千上万个HashMap的ArrayList,它们具有四个键和映射到它们的值,如下所示:
HashMap<String, Object> map = new HashMap<>();
map.put("ID", 1);
map.put("NAME", name);
map.put("WORK_TIME", workTime);
map.put("ACCOUNT", name);
现在有了这些HashMap的ArrayList,我想对具有相同id,姓名和帐户的人的工作时间进行汇总,例如:
HashMap<String, Object> map1 = new HashMap<>();
map1.put("ID", 1);
map1.put("NAME", "Edward");
map1.put("WORK_TIME", 20);
map1.put("ACCOUNT", null);
HashMap<String, Object> map2 = new HashMap<>();
map2.put("ID", 1);
map2.put("NAME", "Krzych");
map2.put("WORK_TIME", 6);
map2.put("ACCOUNT", 123);
HashMap<String, Object> map3 = new HashMap<>();
map3.put("ID", 1);
map3.put("NAME", "Edward");
map3.put("WORK_TIME", 13.5);
map3.put("ACCOUNT", null);
HashMap<String, Object> map4 = new HashMap<>();
map4.put("ID", 2);
map4.put("NAME", "Grzesiek");
map4.put("WORK_TIME", 50);
map4.put("ACCOUNT", null);
HashMap<String, Object> map5 = new HashMap<>();
map5.put("ID", 2);
map5.put("NAME", "Edward");
map5.put("WORK_TIME", 12);
map5.put("ACCOUNT", 123);
[..]
ArrayList<HashMap<String,Object>> arrList = new ArrayList<>();
arrList.put..
结果,我应该获得一个包含4个HashMap的ArrayList,其中只有两个具有相同ID和帐户的Edward HashMap合并为一个工作时间为33.5的单个HashMap。
我想到的唯一一件事是遍历所有映射,比较这三个值,然后成功替换存储在第二个数组列表中的哈希图中的工作时间值 我正在Java 8中工作,我想使用流来完成此操作,这可能吗?还是您看到更好的解决方案?
答案 0 :(得分:0)
此lambda:
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类,因此您可以覆盖equals以符合您的需求,并且可以在一个简单的lambda中映射和汇总工作时间:
Map<Person, Double> result = arrList.stream().collect(Collectors.groupingBy(x -> x, Collectors.summingDouble(Person::getWorkTime)));
Person类的代码:
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)));