添加到我对原始帖子的评论中,这是我想出的代码。显然,它假设您确实想要一个一对多的关系,一个整数映射到 a List<String>
。
public class MappingDemo {
public static void main(String[] args) {
MappingDemo demo = new MappingDemo();
System.out.println("... Using custom collector ...");
demo.dumpMap(demo.getFruitMappingsWithCustomCollector());
System.out.println("... Using 'External' map ...");
demo.dumpMap(demo.getFruitMappingsWithExternalMap());
}
public Map<Integer, List<String>> getFruitMappingsWithCustomCollector(){
// Resulting map is created from within the lambda expression.
return getContent().stream().map(s -> s.split(",\\s"))
.collect(
HashMap::new,
(map, ary) -> map.computeIfAbsent(Integer.parseInt(ary[0]),
k -> new ArrayList<>()).add(ary[1]),
(map1, map2) -> map1.entrySet().addAll(map2.entrySet())
);
}
public Map<Integer,List<String>> getFruitMappingsWithExternalMap(){
// Create the map external from the lambda and add to it.
final Map<Integer,List<String>> fruitMappings = new HashMap<>();
getContent().stream().map(s -> s.split(",\\s"))
.forEach(ary ->
fruitMappings.computeIfAbsent(Integer.parseInt(ary[0]),
k -> new ArrayList<>()).add(ary[1]));
return fruitMappings;
}
public void dumpMap(Map<Integer,List<String>> map){
map.entrySet().forEach(e -> System.out.println(e.getKey() + " -> " + e.getValue()));
}
public List<String> getContent(){
return Arrays.asList("1, Apple",
"1, Pear",
"1, Orange",
"2, Apple",
"3, Melon",
"3, Orange",
"1, Mango",
"3, Star Fruit",
"4, Pineapple",
"2, Pomegranate");
}
}
和输出
...使用自定义收集器...
1 -> [苹果、梨、橙、芒果]
2 -> [苹果、石榴]
3 -> [甜瓜、橙子、杨桃]
4 -> [菠萝]
...使用“外部”地图...
1 -> [苹果、梨、橙、芒果]
2 -> [苹果、石榴]
3 -> [甜瓜、橙子、杨桃]
4 -> [菠萝]
我很确定有人可以做得更好。
getContent
只是一种使用您提供的文本获取值的简单方法。如果您实际上正在Files.readAllLines
阅读. getContent()
File