- Streamlining Your Java Code: How to Convert a List to a LinkedHashMap Using Stream API
- Step 1: Create a List
- Step 2: Convert to a LinkedHashMap
- Step 3: Use the LinkedHashMap
- Conclusion
- Stream to LinkedHashMap :
- 1. Using Collectors.toMap(keyMapper, valueMapper, mergeFunction) :
- StreamToMapUsingCollectorsToMap.java
- 2. Using Collectors.toMap(keyMapper, valueMapper, mergeFunction, supplier) :
- StreamToLinkedHashMapUsingCollectorsToMap.java
- Related Articles:
- References :
- How to Convert Stream to Specific Map Implementation in Java
- Convert Stream to Map
- Convert Stream to TreeMap
- Convert Stream to LinkedHashMap
Streamlining Your Java Code: How to Convert a List to a LinkedHashMap Using Stream API
If you’re working with Java and you find yourself often needing to convert a list to a LinkedHashMap , we have good news for you: the Stream API makes this task easy and streamlined.
In this article, we’ll show you how to use the Stream API to convert a list to a LinkedHashMap in a few simple steps.
Step 1: Create a List
First, you’ll need to create a list that you want to convert to a LinkedHashMap . For the purposes of this example, we’ll use a list of strings:
List list = Arrays.asList("one", "two", "three");
Step 2: Convert to a LinkedHashMap
Next, you can use the stream method to create a stream from the list, and then use the collect method to collect the stream into a LinkedHashMap .
Map map = list.stream() .collect(Collectors.toMap(Function.identity(), Function.identity(), (v1,v2) -> v1, LinkedHashMap::new));
- Function.identity() is used as both the key and value mapping functions
- (v1, v2) -> v1 is a merge function that resolves any key conflicts by using the first value found
- LinkedHashMap::new specifies that we want a LinkedHashMap .
Step 3: Use the LinkedHashMap
Now that you have a LinkedHashMap , you can use it just as you would any other map:
System.out.println(map); // output:
And that’s it! With just a few lines of code, you can easily convert a list to a LinkedHashMap using the Stream API.
Conclusion
Converting a list to a LinkedHashMap can be a common task in Java development, but it doesn’t have to be a complicated one. By using the Stream API, you can streamline the process and make your code more efficient and easier to read. We hope this article has been helpful in showing you how to perform this useful conversion.
Stream to LinkedHashMap :
1. Using Collectors.toMap(keyMapper, valueMapper, mergeFunction) :
- First variant of Collectors.toMap() method accepts 3 input-arguments
- Key mapper – mapping function to produce keys
- Value mapper – mapping function to produce values
- Merge Function – this is used to resolve collisions between values associated with the same key
- Above method helps to convert Stream into Map
- For converting into LinkedHashMap, create LinkedHashMap object and pass above obtained Map as constructor-argument
- LinkedHashMap stores Key-Value pairs according to insertion order of Keys
- Finally, print converted LinkedHashMap pairs to console
StreamToMapUsingCollectorsToMap.java
package net.bench.resources.stream.to.linkedhashmap; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; public class StreamToMapUsingCollectorsToMap < public static void main(String[] args) < // 1. Stream of String tokens StreamnameStream = Stream.of( "Rajiv", "Anbu", "Santosh", "Abdul", "Lingaraj" ); // 2. convert Stream to Map Map map = nameStream .collect(Collectors.toMap( Function.identity(), // 1. actual String as KEY String::length, // 2. String length as their VALUE (key1, key2) -> key1) // 3. duplicate KEY resolver ); // 2.1 print to console System.out.println("1. Stream to Map conversion : \n\n" + map); // 3. convert Map to LinkedHashMap using inter-conversion constructor LinkedHashMap hMap = new LinkedHashMap<>(map); // 3.1 print to console System.out.println("\n\n2. Stream to LinkedHashMap conversion : \n\n" + hMap); > >
1. Stream to Map conversion : 2. Stream to LinkedHashMap conversion :
2. Using Collectors.toMap(keyMapper, valueMapper, mergeFunction, supplier) :
- This is the 2 nd variant of Collectors.toMap() method which accepts 4 input-arguments
- Key mapper – mapping function to produce keys
- Value mapper – mapping function to produce values
- Merge Function – this is used to resolve collisions between values associated with the same key
- Supplier – function which returns a new, empty Map into which the results will be inserted
- Above method helps to convert Stream into HashMap, LinkedHashMap or TreeMap directly or whichever Supplier we pass as 4 th argument
- In the below example, we are passing LinkedHashMap implementation class as method/constructor reference LinkedHashMap::new
- LinkedHashMap stores Key-Value pairs according to insertion order of Keys
- Finally, print converted LinkedHashMap pairs to console
StreamToLinkedHashMapUsingCollectorsToMap.java
package net.bench.resources.stream.to.linkedhashmap; import java.util.LinkedHashMap; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; public class StreamToLinkedHashMapUsingCollectorsToMap < public static void main(String[] args) < // 1. Stream of String tokens StreamnameStream = Stream.of( "Rajiv", "Anbu", "Santosh", "Abdul", "Lingaraj" ); // 2. convert Stream to LinkedHashMap LinkedHashMap lhMap = nameStream .collect(Collectors.toMap( Function.identity(), // 1. actual String as KEY String::length, // 2. String length as their VALUE (key1, key2) -> key1, // 3. duplicate KEY resolver LinkedHashMap::new // 4. implementation-class )); // 2.1 print to console System.out.println("Stream to LinkedHashMap conversion : \n\n" + lhMap); > >
Stream to LinkedHashMap conversion :
Related Articles:
References :
How to Convert Stream to Specific Map Implementation in Java
How can we convert a Stream to a TreeMap or LinkedHashMap or any Map implementation in Java?
Suppose we have a Stream of integers.
StreamInteger> stream = Arrays.asList(1, 2).stream();
Convert Stream to Map
We can use Stream.collect() and Collectors.toMap() to collect stream elements into a map.
MapInteger, Integer> map = stream.collect( Collectors.toMap( num -> getKey(num), num -> getValue(num) ) );
If we’re collecting map entries into another map, we can use the static Map.Entry::getKey and Map.Entry::getValue functions.
MapInteger, Integer> map = stream.collect( Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue ) );
Convert Stream to TreeMap
To convert to a specific map implementation, we’ll need to specify the mergeFunction and mapSupplier , the third and fourth arguments, respectively.
MapInteger, Integer> map = stream.collect( Collectors.toMap( num -> getKey(num), num -> getValue(num), (oldValue, newValue) -> newValue, TreeMap::new ) );
The (oldValue, newValue) -> newValue allows the collector to resolve duplicate keys, and in this case, returns the value of the second key.
The mapSupplier provides a new, empty Map instance into which the results will be inserted.
Convert Stream to LinkedHashMap
Converting to other implementations is just as easy.
MapInteger, Integer> map = stream.collect( Collectors.toMap( num -> getKey(num), num -> getValue(num), (oldValue, newValue) -> newValue, LinkedHashMap::new ) );
General-purpose map implementations include HashMap , TreeMap , and LinkedHashMap . Special-purpose map implementations include EnumMap , WeakHashMap , and IdentityHashMap . There are also concurrent map implementations: ConcurrentMap and ConcurrentHashMap .