使用函数接口(lambdas)从POJO列表中收集值



我如何迭代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(", "));
}

我认为这应该有效(还没有测试)。

最新更新