Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Convert List<String> to Map<String, String>

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!

like image 438
Malsor Avatar asked Feb 12 '26 18:02

Malsor


1 Answers

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));
like image 163
Andy Turner Avatar answered Feb 15 '26 06:02

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!