gpt4 book ai didi

java - 在流上使用 Collections.toMap() 时如何保持列表的迭代顺序?

转载 作者:太空宇宙 更新时间:2023-11-04 12:13:58 24 4
gpt4 key购买 nike

我正在从 List 创建一个 Map,如下所示:

List<String> strings = Arrays.asList("a", "bb", "ccc");

Map<String, Integer> map = strings.stream()
.collect(Collectors.toMap(Function.identity(), String::length));

我想保持与列表中相同的迭代顺序。如何使用 Collectors.toMap() 方法创建 LinkedHashMap

最佳答案

2-parameter version of 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-parameter version ,您可以替换:

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
);
}
}

关于java - 在流上使用 Collections.toMap() 时如何保持列表的迭代顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39598141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com