How to Combine Two Lists into a Map (Java)

What is the best way to combine two lists into a map (Java)?

Since the key-value relationship is implicit via the list index, I think the for-loop solution that uses the list index explicitly is actually quite clear - and short as well.

Java 8: Merge 2 String Lists into Map

You can iterate over the indices of the Lists with an IntStream:

Map<String, String> result =
IntStream.range(0,keys.size())
.boxed()
.collect(Collectors.toMap(i -> keys.get(i), i -> values.get(i)));

Best way in java to merge two lists to one map?

Assuming, that both lists are of equal length and that keys and values have the same index in both lists, then this is an easy approach:

for (int i = 0; i < strings.size(); i++) {
map.put(strings.get(i), integers.get(i));
}

Merge Two Lists based on a condition and push the result to a map using java 8

Here's one way of doing it:

Map<String, String> map = 
sourceList.stream()
.map(source -> targetList.stream()
.filter(dest -> dest.getUserId().equals(source.getUserId()))
.map(dest -> new SimpleEntry<>(source.getPersonaId(), dest.getPersonaId()))
.firstFirst())
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));

You find for each element of the source list a corresponding element of the target list, map these elements to a Map.Entry that contains the two person Ids, and collect all the entries to a Map.

Creating Map composed of 2 Lists using stream().collect in Java

Instead of using an auxiliary list to hold the indices, you can have them generated by an IntStream.

Map<Double, String> map = IntStream.range(0, list1.size())
.boxed()
.collect(Collectors.toMap(i -> list1.get(i), i -> list2.get(i)));

how to combine two ListMapString,Object

You can do the following things:-

  1. Sort both List of maps based on the product_idx number.
  2. define a counter for productLikeRenew and initialize with 0.
  3. Iterate voListResult list until product_idx of voListResult <= product_idx of productLikeRenew.
  4. If product_idx of both of them is equal then combine the result.
  5. Increment the counter.
  6. Repeat steps from 3 to 5 until one of the List is ended.


Related Topics



Leave a reply



Submit