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?

2
  • Possible duplicate of Java 8 List<V> into Map<K, V> Commented Oct 14, 2017 at 1:34
  • @nullpointer not really, its a completely different problem (mapping elements together vs mapping elements with something else) Commented Oct 14, 2017 at 1:43

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.