gpt4 book ai didi

Java 8 lambda : convert Collection to Map of element, 迭代位置

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:11:03 25 4
gpt4 key购买 nike

如何将像 ["a", "b", "c"] 这样的集合转换为像 {"a": 0, "b":1, "c":2} 这样的值是迭代的顺序。在 JDK8 中是否有一个带有流和收集器的单一衬里?老办法是这样的:

    Collection<String> col = apiCall();
Map<String, Integer> map = new HashMap<>();
int pos = 0;
for (String s : collection) {
map.put(s, pos++);
}

最佳答案

如果您不需要并行流,您可以使用 map 的长度作为索引计数器:

collection.stream().forEach(i -> map.put(i, map.size() + 1));

关于Java 8 lambda : convert Collection to Map of element, 迭代位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25041177/

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