如何将字符串列表转换为 LinkedHashMap?
How to convert a list of Strings to a LinkedHashMap?
我有一个列表:
private List <String> list;
我想将其转换为 LinkedHashMap(以保留顺序),这样映射中的前两个值是 LinkedHashMap 条目,依此类推,直到列表成为 LinkedHashMap:
private LinkedHashMap<String, String> linked;
这是我想出来的。诚然,我是 Collectors 实现的新手,所以请多多包涵:
linked = list.stream()
.collect(Collectors.toMap(
Function.identity(),
String::valueOf, //Used to be String::length
LinkedHashMap::new));
这在 LinkedHashMap 构造函数行上给我一个错误:
Cannot resolve constructor of LinkedHashMap
这是列表的示例:
zero
test0
one
test1
two
test2
以及我希望地图的外观:
zero:test0
one:test1
two:test2
谢谢
你错过了merge function:
a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)
但是要使用流 api 用您的预期值填充地图,您可以使用 forEach
方法和 java9
中的 IntStream::iterate
LinkedHashMap<String, String> linked = new LinkedHashMap<>();
IntStream.iterate(0, n -> n < list.size(), n -> n + 2)
.forEach(i -> linked.put(list.get(i), list.get(i + 1)));
为什么要使代码复杂化,一个简单的循环就可以解决问题:
for (int i = 0; i < list.size(); i += 2) {
linked.put(list.get(i), list.get(i + 1));
}
输出
zero:test0
one:test1
two:test2
这是我对 java 8.
的尝试
IntStream.range(0, list.size())
.mapToObj(index -> {
if (index % 2 == 0) {
return new AbstractMap.SimpleImmutableEntry<>(list.get(index), list.get(index + 1));
}
return null;
}
)
.filter(Objects::nonNull)
.collect(Collectors.toMap(AbstractMap.SimpleImmutableEntry::getKey, AbstractMap.SimpleImmutableEntry::getValue));
我有一个列表:
private List <String> list;
我想将其转换为 LinkedHashMap(以保留顺序),这样映射中的前两个值是 LinkedHashMap 条目,依此类推,直到列表成为 LinkedHashMap:
private LinkedHashMap<String, String> linked;
这是我想出来的。诚然,我是 Collectors 实现的新手,所以请多多包涵:
linked = list.stream()
.collect(Collectors.toMap(
Function.identity(),
String::valueOf, //Used to be String::length
LinkedHashMap::new));
这在 LinkedHashMap 构造函数行上给我一个错误:
Cannot resolve constructor of LinkedHashMap
这是列表的示例:
zero
test0
one
test1
two
test2
以及我希望地图的外观:
zero:test0
one:test1
two:test2
谢谢
你错过了merge function:
a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction)
但是要使用流 api 用您的预期值填充地图,您可以使用 forEach
方法和 java9
IntStream::iterate
LinkedHashMap<String, String> linked = new LinkedHashMap<>();
IntStream.iterate(0, n -> n < list.size(), n -> n + 2)
.forEach(i -> linked.put(list.get(i), list.get(i + 1)));
为什么要使代码复杂化,一个简单的循环就可以解决问题:
for (int i = 0; i < list.size(); i += 2) {
linked.put(list.get(i), list.get(i + 1));
}
输出
zero:test0
one:test1
two:test2
这是我对 java 8.
的尝试 IntStream.range(0, list.size())
.mapToObj(index -> {
if (index % 2 == 0) {
return new AbstractMap.SimpleImmutableEntry<>(list.get(index), list.get(index + 1));
}
return null;
}
)
.filter(Objects::nonNull)
.collect(Collectors.toMap(AbstractMap.SimpleImmutableEntry::getKey, AbstractMap.SimpleImmutableEntry::getValue));