Reputation: 165
I have two list both of type Long, say ListA
and ListB
.
I want to merge these into a Map<Long, Long>
such that ListA
becomes key and and ListB
becomes value.
Here catch is I want to add these key value pair to an existing map.
I know how to parse the lists and return a new map object (using Collectors.toMap
). My problem is to add to an existing map, may be something like:
Map<Long, Long> map = new HashMap<Long, Long>;
// ... entries added to map
ListA.stream().forEach(a -> {
map.put(a, <get 0th element of ListB somehow>);
});
Thanks in advance!
Upvotes: 1
Views: 432
Reputation: 120848
Supposing that those lists have the same size:
Map<Long, Long> map = IntStream.range(0, listA.size())
.boxed()
.collect(Collectors.toMap(listA::get, listB::get));
yourOtherMap.putAll(map);
Upvotes: 2
Reputation: 521168
Try this option:
Map<Long, Long> map = new HashMap<>();
IntStream.range(0, ListA.size())
.forEach(i -> {
map.put(ListA.get(i), ListB.get(i));
});
But honestly, I see nothing wrong here with using a regular pre Java 8 enhanced for
loop:
// assuming both lists have the same size
for (int i=0; i < ListA.size(); ++i) {
map.put(ListA.get(i), ListB.get(i);
}
It's concise, easy to read and maintain, and won't turn the head of anyone reviewing your code.
Upvotes: 1