0

I have a List that I am trying to convert to a Map<String, String> using Java 8.

The list is as below

List<String> data = Arrays.asList("Name", "Sam", "Class", "Five", "Medium", "English")

I want a Map<String, String> such that the key value pair will be like

{{"Name", "Sam"}, {"Class", "Five"}, {"Medium", "English"}}

I am trying to achieve this in Java 8 and tried using Instream.range() but did not get the exact result.

IntStream.range(0, data.size() - 1).boxed()
                .collect(Collectors.toMap(i -> data.get(i), i -> data.get(i + 1)));

The issue with the above code is the result also gives an output as {"Sam", "Class"}

3 Answers 3

1

Here is one way.

  • generate a range of values, i, from 0 to size/2.
  • then use i*2 and i*2 + 1 as the indices into the list.
List<String> data = Arrays.asList("Name", "Sam", "Class",
        "Five", "Medium", "English");

Map<String, String> map = IntStream
        .range(0,data.size()/2).boxed()
        .collect(Collectors.toMap(i -> data.get(i*2),
                i -> data.get(i*2+1)));

map.entrySet().forEach(System.out::println);

prints

Medium=English
Class=Five
Name=Sam
Sign up to request clarification or add additional context in comments.

Comments

1

The issue here is that you're stepping through every index, whereas you just want to step through every other index. You could either filter the odd values, adding .filter(i->i%2==0) to your stream - or use IntStream.iterate() to get the numbers you want directly:

IntStream.iterate(0, i->i<data.size()-1,i->i+2)

Comments

1

You have to iterate every 2 elements, therefore the steps to do are 3 equal to 6 (list size) / 2 (step size).

So iterate by steps and not by elements and you can find the two elements of each step in the collect phase. Here is the example:

IntStream.range(0, data.size() / 2)
         .boxed()
         .collect(Collectors.toMap(i -> data.get(i * 2), i -> data.get(i * 2 + 1)));

2 Comments

How is that different from my answer?
The code is equal, the explanation is different. When I was writing the solution, I did not see that meanwhile you wrote a similar answer.

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.