0

I have two lists:

List<String> ids
List<String> names

The task is to create one Map<String,String> out of these two lists, preferably using Java 8. Unfortunatly, I did not find how to make it when we have lists with String type.

1
  • 1
    The question is not clear. Which should be the key - I guess ids? Are the ids unique. Are the lists the same size? How should they be grouped? Commented Nov 6, 2018 at 17:38

1 Answer 1

1

Assuming both the lists have the same size & ids are unique & ids are the keys of the map and names are corresponding values, you can use the following code to create a map:

Map<String,String> idsNames = IntStream.range(0,ids.size())
        .mapToObj(i -> new AbstractMap.SimpleEntry<>(ids.get(i),names.get(i)))
        .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey,
                AbstractMap.SimpleEntry::getValue));
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, it works. Sorry if my question was not very clear.
There's no need to create an intermediate Map.Entry for each i. Just using IntStream.range(0,ids.size()).boxed().collect(Collectors.toMap(ids::get, names::get)) should suffice. It's also worth mentioning that this approach works well if both lists are random access, i.e. ArrayList.

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.