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 List
s 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:-
- Sort both List of maps based on the product_idx number.
- define a counter for productLikeRenew and initialize with 0.
- Iterate voListResult list until product_idx of voListResult <= product_idx of productLikeRenew.
- If product_idx of both of them is equal then combine the result.
- Increment the counter.
- Repeat steps from 3 to 5 until one of the List is ended.
Related Topics
How to Force Browser to Download File
Setting Jvm Heap Size at Runtime
Difference Between & and && in Java
Faster Alternatives to Java's Reflection
Why Does Stream<T> Not Implement Iterable<T>
How to Store Java Objects in Httpsession
How to Set Request Encoding in Tomcat
Compiler Error When Declaring a Variable Inside If Condition and No Curly Braces
Spring Resttemplate Get with Parameters
Choose Between Executorservice's Submit and Executorservice's Execute
Why Does Arraylist Have "Implements List"
CSV Parsing in Java - Working Example
Retrieving a List from a Java.Util.Stream.Stream in Java 8
Replace the Last Part of a String
How to Inject an Object into Jersey Request Context