Java8 entryset的stream map操作

Map<Long, A> aMap = aGateway.getAMap(someRequest);

Map<Integer, B> resultMap = aMap.entrySet()
                                .stream()
                                .collect(Collectors.toMap(
                                         entry -> entry.getKey().intValue(), 
                                         entry -> someOp(entry.getValue())));

看到这段代码,觉得可以。Java8中先用entrySet, stream变为流,再collect,其中每个entry: toMap之后,map过程中getKey, getValue获取到每个key和value再进行操作。

本质上是

<K, V> Collector<? super Map.Entry<K, V>, ?, Map<K, V>> toMap() {
  return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}

类似地(参考StackOverflow这个帖子),e.g.

private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) {
    int subLength = prefix.length();
    return input.entrySet().stream()
            .collect(Collectors.toMap(
                   entry -> entry.getKey().substring(subLength), 
                   entry -> AttributeType.GetByName(entry.getValue())));
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容