在流上使用Collections.toMap()时,如何保持List的迭代顺序?
我创建一个Map
从List
如下:
List<String> strings = Arrays.asList("a", "bb", "ccc");Map<String, Integer> map = strings.stream()
.collect(Collectors.toMap(Function.identity(), String::length));
我想保持与中相同的迭代顺序List
。如何LinkedHashMap
使用该Collectors.toMap()
方法创建一个?
回答:
在2个参数的版本Collectors.toMap()
采用的是HashMap
:
public static <T, K, U> Collector<T, ?, Map<K,U>> toMap( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper)
{
return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
}
要使用4参数版本,您可以替换:
Collectors.toMap(Function.identity(), String::length)
与:
Collectors.toMap( Function.identity(),
String::length,
(u, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", u));
},
LinkedHashMap::new
)
为了使它更简洁,请编写一个新toLinkedMap()
方法并使用该方法:
public class MoreCollectors{
public static <T, K, U> Collector<T, ?, Map<K,U>> toLinkedMap(
Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper)
{
return Collectors.toMap(
keyMapper,
valueMapper,
(u, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", u));
},
LinkedHashMap::new
);
}
}
以上是 在流上使用Collections.toMap()时,如何保持List的迭代顺序? 的全部内容, 来源链接: utcz.com/qa/429681.html