从列表中收集对象的多个属性的简单方法

问题描述 投票:0回答:1

如果我有一个具有多个相同类型属性的对象列表,那么收集该列表的所有属性的最佳方法是什么?

        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()));
dictionary collections attributes java-stream
1个回答
0
投票

像这样尝试一下。使用

mapMulti
将每个
long
放入流中。

Set<Long> allIds = is.stream().<Long>mapMulti((issue, consumer)-> {
            consumer.accept(issue.getId1());
            consumer.accept(issue.getId2());
  }).collect(Collectors.toSet());
 
© www.soinside.com 2019 - 2024. All rights reserved.