如何迭代 POJO 类列表,以标准方式收集某些方法的结果以避免复制过去? 我想要这样的代码:
//class 'Person' has methods: getNames(), getEmails()
List<Person> people = requester.getPeople(u.getId());
String names = merge(people, Person::getNames);
String emails = merge(people, Person::getEmails);
而不是这种复制粘贴的逻辑:
List<Person> people = requester.getPeople(u.getId());
Set<String> namesAll = new HashSet<>();
Set<String> emailsAll = new HashSet<>();
for (Person p : people) {
if(p.getNames()!=null) {
phonesAll.addAll(p.getNames());
}
if(p.getEmails()!=null) {
emailsAll.addAll(p.getEmails());
}
}
String names = Joiner.on(", ").skipNulls().join(namesAll);
String emails = Joiner.on(", ").skipNulls().join(emailsAll);
因此,是否可以实现一些标准方法来迭代和处理列表中可重用的 POJO 特殊方法?
最佳答案
如果我理解正确的话,你想要这样的东西:
String names = people.stream().flatMap(p->p.getNames().stream()).distinct().collect(Collectors.joining(", "));
现在,如果您想节省为每个属性键入该行,您可以按照您的建议使用此 merge
方法:
public static String merge (List<Person> people, Function<Person, Collection<String>> mapper)
{
return people.stream().flatMap(p->mapper.apply(p).stream()).distinct().collect(Collectors.joining(", "));
}
这将使您的第一个代码片段工作。
现在,您可以将此方法设为通用:
public static <T> String merge (List<T> list, Function<T, Collection<String>> mapper)
{
return list.stream().flatMap(p->mapper.apply(p).stream()).distinct().collect(Collectors.joining(", "));
}
我认为这应该有效(尚未测试)。
关于java - 使用函数式接口(interface) (lambda) 从 POJO 列表中收集值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34518965/