How to convert List to Map with indexes using stream - Java 8?(如何使用流将列表转换为带有索引的地图 - Java 8?)
问题描述
我已经创建了计算字母表中每个字符的方法.我正在学习流(函数式编程)并尝试尽可能多地使用它们,但在这种情况下我不知道该怎么做:
I've created method whih numerating each character of alphabet. I'm learning streams(functional programming) and try to use them as often as possible, but I don't know how to do it in this case:
private Map<Character, Integer> numerateAlphabet(List<Character> alphabet) {
Map<Character, Integer> m = new HashMap<>();
for (int i = 0; i < alphabet.size(); i++)
m.put(alphabet.get(i), i);
return m;
}
那么,如何使用 Java 8 的流重写它?
So, how to rewrite it using streams of Java 8?
推荐答案
避免有状态索引计数器,例如其他答案中提出的基于 AtomicInteger
的解决方案.如果流是并行的,它们将失败.相反,流过索引:
Avoid stateful index counters like the AtomicInteger
-based solutions presented in other answers. They will fail if the stream were parallel. Instead, stream over indexes:
IntStream.range(0, alphabet.size())
.boxed()
.collect(toMap(alphabet::get, i -> i));
以上假设传入列表不应包含重复字符,因为它是字母表.如果您有重复元素的可能性,那么多个元素将映射到同一个键,然后您需要指定 合并函数.例如,您可以使用 (a,b) ->b
或 (a,b) ->a
作为 toMap
方法的第三个参数.
Above assumes that the incoming list is not supposed to have duplicate characters since it's an alphabet. If you have possibility of duplicate elements then multiple elements will map to same key and then you need to specify merge function. For example you can use (a,b) -> b
or (a,b) ->a
as the third parameter to toMap
method.
这篇关于如何使用流将列表转换为带有索引的地图 - Java 8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用流将列表转换为带有索引的地图 - Java 8?
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01