[英]Convert List of Strings into Map using Java-8 Streams API
I have List 我有名单
List<String> cars = Arrays.asList("Ford", "Focus", "Toyota", "Yaris","Nissan", "Micra", "Honda", "Civic");
Now, can I convert this List into Map where I get ford = focus, Toyota = yaris, Nisan = Micra, Honda = Civic using Java 8 Streams API? 现在,我可以将此List转换为Map,其中我获得ford = focus,Toyota = yaris,Nisan = Micra,Honda = Civic使用Java 8 Streams API?
Here is an example on how you could do it : 这是一个如何做到这一点的例子:
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)));
Basically, just iterates over every 2 elements and maps it with the next one. 基本上,只需迭代每2个元素并将其映射到下一个元素。
Note that if the number of elements is not even, it won't take into consideration the last element. 请注意,如果元素数不均匀,则不会考虑最后一个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.