java8 stream op List <list <long>&gt;

时间:2017-07-25 07:48:23

标签: list dictionary java-stream

我有一个定义为List<List<Long>> dataSet的数据集,dataSet(List)中的元素有8个子emelents,我想通过dataSet使用索引0元素组,最后构建一个map map&gt ;,怎么做这个? 旧代码是:

List<List<Long>> dataSet = .....; 
Map<Long, Set<Long>> a = new HashMap<>();
for (List<Long> data : dataSet) {
    Long userId = data.get(0);
    Long targetId = date.get(7);
    if (a.containsKey(userId)) {
        a.get(userId).add(targetId);
    } else {
        Set<Long> ids = new HashSet<>();
        ids.add(targetIds);
        a.put(userId, ids);
    }
}

1 个答案:

答案 0 :(得分:0)

我已经编写了一个适合您需求的Collector - 接口的具体实现。

  

注意:此收藏家也可以并行工作,非常方便

public class MapCollector implements Collector<List<Long>, Map<Long, Set<Long>>, Map<Long, Set<Long>>>{

    @Override
    public Supplier<Map<Long, Set<Long>>> supplier(){
        return HashMap::new;
    }

    @Override
    public BiConsumer<Map<Long, Set<Long>>, List<Long>> accumulator(){
        return ( m, l ) -> {
            Set<Long> longs = m.get(l.get(0));
            if( longs == null ){
                longs = new HashSet<>();
            }
            longs.add(l.get(7));
            m.put(l.get(0), longs);
        };
    }

    @Override
    public BinaryOperator<Map<Long, Set<Long>>> combiner(){
        return ( m1, m2 ) -> {
            m2.forEach(( k, v ) -> {
                Set<Long> longs = m1.get(k);
                if( longs == null ){
                    longs = v;
                } else{
                    longs.addAll(v);
                }
                m1.put(k, longs);
            });
            return m1;
        };
    }

    @Override
    public Function<Map<Long, Set<Long>>, Map<Long, Set<Long>>> finisher(){
        return UnaryOperator.identity();
    }

    @Override
    public Set<Characteristics> characteristics(){
        return EnumSet.of(Characteristics.IDENTITY_FINISH, Characteristics.UNORDERED, Characteristics.CONCURRENT);
    }
}

您可以通过以下方式使用它:Map<Long, Set<Long>> map = dataSet.stream().collect(new MapCollector());

希望这对你有用;)