我认为java中最优雅的方式是使用stream和Collectors。
你可以这样实现:
List<Tuple2<String, String>> list = new ArrayList<>();
list.add(new Tuple2<>("first", "second"));
list.add(new Tuple2<>("third", "four"));
list.add(new Tuple2<>("five", "six"));
list.add(new Tuple2<>("seven", "eight"));
list.add(new Tuple2<>("nine", "ten"));
System.out.println("List of Tuple2s:" + list);
//convert list of tupples to Map with one line
Map<String, String> resultMap = list.stream()
.collect(Collectors.toMap(Tuple2::_1, Tuple2::_2));
System.out.println("Map of Tuples2s: "+resultMap);
输出:
List of Tuple2s:[(first,second), (third,four), (five,six), (seven,eight), (nine,ten)]
Map of Tuples2s: {nine=ten, third=four, seven=eight, five=six, first=second}
但是重复键呢?当我们将另一个项目添加到列表中时,例如:list.add(new Tuple2<>("first", "ten")); 发生异常:
线程“主”java.lang.IllegalStateException 中的异常:重复
关键秒在
java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
在 java.util.HashMap.merge(HashMap.java:1253)
如果您不确定是否可以复制,您可以这样做:
Map<String, String> resultMap = list.stream()
.collect(Collectors.toMap(Tuple2::_1, Tuple2::_2,
(x, y) -> {
System.out.println("duplicate key!");
return x;
}));
并避免覆盖Map 中的项目。
输出:
List of Tuple2s:[(first,second), (third,four), (five,six), (seven,eight), (nine,ten), (first,ten)]
duplicate key!
Map of Tuples2s: {nine=ten, third=four, seven=eight, five=six, first=second}