【问题标题】:java8 stream op List<List<Long>>java 8 流 List<List<Long>>
【发布时间】:2017-07-25 07:48:23
【问题描述】:

我有一个数据集定义为List&lt;List&lt;Long&gt;&gt; dataSet,dataSet(List)中的元素有8个子元素,我想用数据集索引0元素组,最后建立一个地图地图>,怎么做? 旧代码是:

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);
    }
}

【问题讨论】:

  • 您的旧代码根本无法运行。您正在访问其范围之外的 userId 和 targetId 变量(for 循环)。您可能需要更正旧代码。这将有助于我们更好地理解需求。
  • 对不起,这是我的错……

标签: list dictionary java-stream


【解决方案1】:

我已经编写了适合您需求的Collector-interface 的具体实现。

注意:这个收集器也可以并行工作,非常方便

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&lt;Long, Set&lt;Long&gt;&gt; map = dataSet.stream().collect(new MapCollector());

希望这对你有用;)

【讨论】:

  • 谢谢你的帮助,我觉得这个答案对我有用!
  • @QinyiZhang 很高兴听到这个消息:)
猜你喜欢
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
相关资源
最近更新 更多