1

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?

Paul Lemarchand
  • 2,068
  • 1
  • 15
  • 27
meticulous_guy
  • 133
  • 1
  • 1
  • 10
  • Possible duplicate of [Java 8 List into Map](https://stackoverflow.com/questions/20363719/java-8-listv-into-mapk-v) – Naman Oct 14 '17 at 01:34
  • @nullpointer not really, its a completely different problem (mapping elements together vs mapping elements with something else) – Paul Lemarchand Oct 14 '17 at 01:43

1 Answers1

3

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.

Paul Lemarchand
  • 2,068
  • 1
  • 15
  • 27
  • Thanks a lot, Paul for the help. I tried my problem with solution suggested by @nullpointer. But it is way to confusing for people who has less knowledge of how lambda works. And my problem is entirely different than the similar questions asked here before. Moreover, I wasn't hoping to get answer of my question as I find moderators here extremely bossy and bully. But you saved my life. Thanks again. :) – meticulous_guy Oct 14 '17 at 15:09
  • @meticulous_guy :) – Paul Lemarchand Oct 14 '17 at 18:58