使用 Java-8 Streams API 将字符串列表转换为 Map

2022-01-08 00:00:00 hashmap java-8 java java-stream

我有清单

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.

相关文章