我有清单
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!