如果我有一个具有多个相同类型属性的对象列表,那么收集该列表的所有属性的最佳方法是什么?
class Issue {
Long id1;
Long id2;
//with appropriate getters
}
List<Issue> is = //some list of Issue
// Is there a better way to do the following?
Set<Long> allIds = is.stream().map(i->i.getId1()).collect(Collectors.toSet());
allIds.addAll(is.stream().map(i->i.getId2()).collect(Collectors.toSet()));
像这样尝试一下。使用
mapMulti
将每个 long
放入流中。
Set<Long> allIds = is.stream().<Long>mapMulti((issue, consumer)-> {
consumer.accept(issue.getId1());
consumer.accept(issue.getId2());
}).collect(Collectors.toSet());