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!
-
1Just iterate over the list (in steps of 2) and put everything inside the map. It's only two lines of code.Aleksandr– Aleksandr2018年03月28日 10:22:01 +00:00Commented Mar 28, 2018 at 10:22
2 Answers 2
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
nafas
this definitely answers the OP, but I say the question is XY problem to be begin with
Malsor
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.
Andy Turner
@Malsor the first two options are preferable to the third: they are clear, efficient and idiomatic.
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
Andy Turner
You can link directly to specific answers (use the "share" link under the specific answers.
Explore related questions
See similar questions with these tags.
lang-java