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.
来源:https://stackoverflow.com/questions/46739038/convert-list-of-strings-into-map-using-java-8-streams-api