Convert List of Strings into Map using Java-8 Streams API(使用 Java-8 Streams API 将字符串列表转换为 Map)
问题描述
我有清单
List<String> cars = Arrays.asList("Ford", "Focus", "Toyota", "Yaris","Nissan", "Micra", "Honda", "Civic");
现在,我可以使用 Java 8 Streams API 将这个列表转换为我得到 Ford = focus、Toyota = yaris、Nisan = Micra、Honda = Civic 的 Map 吗?
Now, can I convert this List into Map where I get ford = focus, Toyota = yaris, Nisan = Micra, Honda = Civic using Java 8 Streams API?
推荐答案
下面是一个例子:
Map<String, String> carsMap =
IntStream.iterate(0, i -> i + 2).limit(cars.size() / 2)
.boxed()
.collect(Collectors.toMap(i -> cars.get(i), i -> cars.get(i + 1)));
基本上,只需遍历每 2 个元素并将其映射到下一个元素.
注意,如果元素个数不偶数,则不会考虑最后一个元素.
Basically, just iterates over every 2 elements and maps it with the next one.
Note that if the number of elements is not even, it won't take into consideration the last element.
这篇关于使用 Java-8 Streams API 将字符串列表转换为 Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Java-8 Streams API 将字符串列表转换为 Map


基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01