本文介紹了使用 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!