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!
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With