Convert from Map to List in Java 8
Ngày đăng:
14/12/2021
Trả lời:
0
Lượt xem:
228
Show Learn how to convert Map to List in java 8. Explore different ways to convert HashMap to ArrayList. map.keySet().stream().collect(Collectors.toList()) 1.OverviewIn this article, You'll learn how to convert Map to List in java and Stream API examples in java 8. Let us explore the different ways to convert HashMap to ArrayList. ArrayList is to store the objects in insertion order and allow duplicates HashMap is a collection that is used to store the key/value pairs. 2. Example 1: Convert All Map Keys into ListUse the map.keyset() method to get all keys as Set and pass to the ArrayList constructor. package com.javaprogramto.java8.maptolist;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MapKeysToListExample {
public static void main(String[] args) {
Map Output: 100
101
102
3. Example 2: Convert All Map Values into ListUse the map.values() method to get all values as Set and pass to the ArrayList constructor. import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MapValuesToListExample {
public static void main(String[] args) {
Map Output: modi
trump
putin
4. Example 3: Java 8 Convert All Map Keys and Values into ListInstead of using the ArrayList constructor, we are using stream() method to convert HashMap to ArrayList. package com.javaprogramto.java8.maptolist;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Java8MapToListExample {
public static void main(String[] args) {
Map Output: Map keys List :
35
20
40
30
15
Map values list :
payaya
mango
jack fruit
gauva
apple
removing odd even fruit id's as list :
20
40
30
First converted HashMap keys and values to stream using stream() method and converted it to List using collect() method passing the Colletors.toList() method. At the end, filter the odd number id's from key's of HashMap using filter() method. 5. Example 4: Convert All Map Keys into List using HashMap.entrySet()Above examples are based on the Map keyset() and values() methods. But, Map has another method entrySet() which returns Set Let us see and learn how to use the entrySet() method in java 8 to convert Map into 2 separate lists. This is not a common scenario. import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Java8EntrySetMapToListExample {
public static void main(String[] args) {
Map Output: Keys list : [30, 15]
Values list : [gauva, apple]
6. ConclusionIn this article, you've seen how to convert HashMap to ArrayList with 4 examples and using java 8 stream api. All examples are over GitHub. MapKeysToListExample.java MapValuesToListExample.java Java8MapToListExample.java Java8EntrySetMapToListExample.java Java 8 filter() Java 8 List forEach Examples |