我在数据库中有一个Person表,相关的域类如下所示:
public class Person {
private String firstName;
private String secondName;
private String city;
private String country;
private int age;
private int hits;
// accessors
}
数据库表将有同一个人的多行,我需要使用Java 8聚合每个行的命中.
人员由以下字段唯一标识: firstName, secondName, city, country个
我写了下面的逻辑,它给了我预期的结果
public void generateReport(List<PersonDTO> persons) {
Map<String, Integer> personHitCount =
persons
.stream()
.collect(Collectors.groupingBy(l -> getPersonKey(l), Collectors.summingInt(Person::getHits)));
List<Person> reportRecords =
persons
.stream().collect(Collectors.toMap(l -> getPersonKey(l), Function.identity(), (o1, o2) -> o1))
.entrySet()
.stream()
.filter(e -> personHitCount.containsKey(e.getKey()))
.map(e -> transform(e.getValue(), personHitCount.get(e.getKey())))
.collect(Collectors.toList());
reportRecords.stream().forEach(System.out::println);
}
private Person transform(Person personDTO, int count) {
return new Person(
personDTO.getFirstName(),
personDTO.getSecondName(),
personDTO.getCity(),
personDTO.getCountry(),
personDTO.getAge(),
count);
}
private String getPersonKey(Person person) {
return new StringJoiner("-")
.add(person.getFirstName())
.add(person.getSecondName())
.add(person.getCity())
.add(person.getCountry())
.toString();
}
我不确定,这是否是一个好的和性能的方法,因为我循环两次人员列表.请您对这段代码提出任何改进或更好的方法.