如何用Java Stream将List<Snippet>转为双层Map嵌套List的结构
解决方法
你现有代码的问题是第二层使用了Collectors.toMap,该收集器的value映射为单个对象,遇到同page的多个Snippet还会抛出重复键异常。要得到内层为List<Snippet>的结构,把第二层的toMap替换为Collectors.groupingBy即可,groupingBy默认会将同组元素收集为List:
List<Snippet> input = ....; Map<Integer, Map<Integer, List<Snippet>>> result = input.stream() .collect(Collectors.groupingBy( Snippet::getDocId, Collectors.groupingBy(Snippet::getPage) ));
可选扩展
如果你需要内层List用指定的集合实现(比如要保持插入顺序用LinkedList),可以给第二层groupingBy指定下游收集器:
Map<Integer, Map<Integer, List<Snippet>>> result = input.stream() .collect(Collectors.groupingBy( Snippet::getDocId, Collectors.groupingBy( Snippet::getPage, Collectors.toCollection(LinkedList::new) ) ));
内容的提问来源于stack exchange,提问作者Kevin Day
相关产品推荐
相关产品推荐

