使用Java-8 Streams API将字符串列表转换为映射 [英] Convert List of Strings into Map using Java-8 Streams API

查看:149
本文介绍了使用Java-8 Streams API将字符串列表转换为映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有List

List<String> cars = Arrays.asList("Ford", "Focus", "Toyota", "Yaris","Nissan", "Micra", "Honda", "Civic");

现在,我可以将此列表转换为我获得ford = focus,Toyota = yaris,Nisan = Micra,Honda =使用Java 8 Streams API的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?

推荐答案

下面是一个关于如何做到的例子: p>

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)));

基本上,每迭代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将字符串列表转换为映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆