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!

Malsor
  • 103
  • 1
  • 8
  • 1
    Just iterate over the list (in steps of 2) and put everything inside the map. It's only two lines of code. – Aleksandr Mar 28 '18 at 10:22

2 Answers2

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));
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • this definitely answers the OP, but I say the question is XY problem to be begin with – nafas Mar 28 '18 at 10:23
  • 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 Mar 28 '18 at 10:55
  • @Malsor the first two options are preferable to the third: they are clear, efficient and idiomatic. – Andy Turner Mar 28 '18 at 11:26
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).

Ondra K.
  • 2,767
  • 4
  • 23
  • 39
  • You can [link directly to specific answers](https://stackoverflow.com/a/20507988/3788176) (use the "share" link under the specific answers. – Andy Turner Mar 28 '18 at 10:30