Mak
Mak

Reputation: 165

Merge two list of type Long and add to existing map in java 8

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

Answers (2)

Eugene
Eugene

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

Tim Biegeleisen
Tim Biegeleisen

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));
    });

Demo

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

Related Questions