Pages

Sunday, August 16, 2020

Java 8 – Convert Map to List (HashMap to ArrayList)

1.Overview


In 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.

Java 8 – Convert Map to List (HashMap to ArrayList)


2. Example 1: Convert All Map Keys into List


Use 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<Integer,String> idNames = new HashMap<>();

        idNames.put(100, "modi");
        idNames.put(101, "trump");
        idNames.put(102, "putin");

        List<Integer> ids =new ArrayList<>(idNames.keySet());

        ids.forEach(id -> System.out.println(id));
    }
}

Output:
100
101
102

3. Example 2: Convert All Map Values into List


Use 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<Integer,String> idNames = new HashMap<>();

        idNames.put(100, "modi");
        idNames.put(101, "trump");
        idNames.put(102, "putin");

        //converting all values from map to list.
        List<String> ids =new ArrayList<>(idNames.values());

        ids.forEach(id -> System.out.println(id));
    }
}

Output:

modi
trump
putin

4. Example 3: Java 8 Convert All Map Keys and Values into List


Instead 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<Integer, String> fruites = new HashMap<>();

        fruites.put(15, "apple");
        fruites.put(20, "mango");
        fruites.put(30, "gauva");
        fruites.put(35, "payaya");
        fruites.put(40, "jack fruit");

        //java 8 - convert all keys to map
        List<Integer> keysList = fruites.keySet().stream().collect(Collectors.toList());

        System.out.println("Map keys List :");

        for (Integer integer : keysList) {
            System.out.println(integer);
        }

        // java 8 - convert all keys to map
        List<String> valuesList = fruites.values().stream().collect(Collectors.toList());

        System.out.println("Map values list :");

        for (String s : valuesList) {
            System.out.println(s);
        }

        System.out.println("removing odd even fruit id's as list : ");

        List<Integer> evenList = fruites.keySet().stream().filter(id -> id % 2 == 0).collect(Collectors.toList());
        evenList.forEach(id -> System.out.println(id));
    }
}
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<Entry<K, V>>.

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<Integer, String> fruites = new HashMap<>();

        fruites.put(15, "apple");
        fruites.put(20, "mango");
        fruites.put(30, "gauva");
        fruites.put(35, "payaya");
        fruites.put(40, "jack fruit");

        List<String> valuesList = new ArrayList<>();

        List<Integer> keyList = fruites.entrySet().stream().filter(e -> e.getKey() % 15 == 0).peek(
                e -> valuesList.add(e.getValue())
        ).map(e-> e.getKey()).collect(Collectors.toList());

        System.out.println("Keys list : "+keyList);
        System.out.println("Values list : "+valuesList);
    }
}

Output:
Keys list : [30, 15]
Values list : [gauva, apple]

6. Conclusion


In 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.


No comments:

Post a Comment

Please do not add any spam links in the comments section.