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?
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.
Note that if the number of elements is not even, it won't take into consideration the last element.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.