2

Is there a nice way to convert/transform a list of Strings (with Collectos API?) into a HashMap?

StringList and Map:

List<String> entries = new ArrayList<>();
HashMap<String, String> map = new HashMap<>();

...

My StringList contains Strings like:

 entries.add("id1");
 entries.add("name1, district");
 entries.add("id2");
 entries.add("name2, city");
 entries.add("id3");
 entries.add("name3");

Output should be:

{id1=name1, district, id2=name2, city, id3=name3}

Thank you!

asked Mar 28, 2018 at 10:19
1
  • 1
    Just iterate over the list (in steps of 2) and put everything inside the map. It's only two lines of code. Commented Mar 28, 2018 at 10:22

2 Answers 2

9

You don't need an external library, it's pretty easy:

for (int i = 0; i < entries.size(); i += 2) {
 map.put(entries.get(i), entries.get(i+1));
}

Or, a more efficient way with non-random access lists would be:

for (Iterator<String> it = entries.iterator(); it.hasNext();) {
 map.put(it.next(), it.next());
}

Or, using streams:

IntStream.range(0, entries.size() / 2)
 .mapToObj(i -> new SimpleEntry<>(entries.get(2*i), entries.get(2*i+1))
 .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
answered Mar 28, 2018 at 10:20

3 Comments

this definitely answers the OP, but I say the question is XY problem to be begin with
Thank you for your prompt reply! I also tried the first two options. I was wondering if there is another way, like your third solution.
@Malsor the first two options are preferable to the third: they are clear, efficient and idiomatic.
0

Andy's answer definitely works and it's a nice three liner, however this answer might explain how to do it with Stream API).

answered Mar 28, 2018 at 10:28

1 Comment

You can link directly to specific answers (use the "share" link under the specific answers.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.