Java 8 将二维数组转换为具有键重复检查的映射
Java 8 Convert 2D array into Map with key duplication check
在 java 8
中如何使用 stream()
将 2D array
转换为地图。如果键值已经存在,它也应该更新值。
String[][] array=new String[][]{{"a","b"},{"a","c"},{"b","d"}};
HashMap<String,String> map=new HashMap<String,String>();
for(String[] arr:array){
map.put(arr[0],arr[1]);
}
我试过了
map=Arrays.stream(array).collect(Collectors.toMap(x->x[0],x->x[1]));
错误
Error:(38, 45) java: incompatible types: inference variable R has
incompatible bounds
equality constraints: java.util.Map
upper bounds: java.util.HashMap,java.lang.Object
添加合并重复键的运算符:
String[][] array = new String[][]{{"a", "b"}, {"a", "c"}, {"b", "d"}};
Map<String, String> m = Arrays.stream(array)
.collect(Collectors.toMap( kv -> kv[0],
kv -> kv[1],
(oldV, newV) -> newV)
));
有一天格式化这些单行将成为一个问题..
在 java 8
中如何使用 stream()
将 2D array
转换为地图。如果键值已经存在,它也应该更新值。
String[][] array=new String[][]{{"a","b"},{"a","c"},{"b","d"}};
HashMap<String,String> map=new HashMap<String,String>();
for(String[] arr:array){
map.put(arr[0],arr[1]);
}
我试过了
map=Arrays.stream(array).collect(Collectors.toMap(x->x[0],x->x[1]));
错误
Error:(38, 45) java: incompatible types: inference variable R has incompatible bounds equality constraints: java.util.Map upper bounds: java.util.HashMap,java.lang.Object
添加合并重复键的运算符:
String[][] array = new String[][]{{"a", "b"}, {"a", "c"}, {"b", "d"}};
Map<String, String> m = Arrays.stream(array)
.collect(Collectors.toMap( kv -> kv[0],
kv -> kv[1],
(oldV, newV) -> newV)
));
有一天格式化这些单行将成为一个问题..