List map to list java 8

A Map is an object that maps keys to values or is a collection of attribute-value pairs. The list is an ordered collection of objects and the List can contain duplicate values. The Map has two values [a key and value], while a List only has one value [an element]. So we can generate two lists as listed:

  • List of values and
  • List of keys from a Map.

Let us assume “map” is the instance of Map, henceforth as usual we all know it contains set and value pairs. so they are defined as follows: 

  • map.values[] will return a Collection of the map’s values.
  • map.keySet[] will return a set of the map’s keys.

Methods:

  1. Passing sets of keys inside ArrayList constructor parameter
  2. Passing collection of map values generated by map.values[] method to the ArrayList constructor parameter
  3. Using Streams API [only applicable after JDK 8 and onwards]

Let us discuss each of them

Methods 1: Passing sets of keys inside ArrayList constructor parameter

Procedure: We can convert Map keys to List of Keys bypassing set of map keys generated by map.keySet[] method to the ArrayList constructor parameter as shown below

map.values[]; // Now here e will pass sets of keys of our map, so it becomes map.values[map.keySet[]]; // Now we just need to store it into List, so creating object List ListofKeys = new ArrayList[map.keySet[]]; // Now we are done with conversion.

Syntax: Henceforth it as follows:

List ListofKeys = new ArrayList[map.keySet[]];

Method 2: List ListofKeys = new ArrayList[map.keySet[]];

We can convert Map keys to a List of Values by passing a collection of map values generated by map.values[] method to ArrayList constructor parameter.

Syntax: Henceforth it is as follows:

List Listofvalues = new ArrayList[map.values[]];

Example

import java.util.*;

class GFG {

    public static void main[String[] args]

    {

        HashMap hs = new HashMap[];

        hs.put["Geeks", 1];

        hs.put["for", 2];

        hs.put["Geeks", 3];

        hs.put["Computer", 4];

        hs.put["Science", 5];

        hs.put["Portal", 6];

        MapValuesToList obj = new MapValuesToList[hs];

        List mapvaltolist = obj.mapvaltolist[hs];

        for [Integer integerList : mapvaltolist] {

            System.out.println[integerList];

        }

    }

    public List

    mapvaltolist[Map map]

    {

        Collection val = map.values[];

        ArrayList al = new ArrayList[values];

        return al;

    }

}

Output:

1 2 3 4 5 6

Method 3: Using Streams API

The stream[] method returns a stream of the keys from the Set of the map keys returned by Map.keySet[]. The collect[] method of the Stream class collects the stream of keys in a List.The Collectors.toCollection[ArrayList::new] passed to the collect[] method to collect as new ArrayList. One can also use Stream API to convert map keys and values to respective lists. the syntax is as provided below as follows:

List ListofKeys = map.keyset[].stream[].collect[Collectors.toCollection[ArrayList::new]];List Listofvalues= map.values[].stream[].collect[Collectors.toCollection[ArrayList::new]];

Note: You can collect elements of Stream in an ArrayList, LinkedList, or any other List implementation.

Implementation:

Given RollNo and Student Name of N students as input. First, we create a Map where Rollno is key because Rollno is unique and Name as Value for Map then convert this map to list of values and keys respectively. Where the generated list of keys contains RollNo of students and list of Values contains Name of Students.

Example

import java.util.*;

import java.util.stream.*;

class GFG {

    public static void main[String[] args]

    {

        Scanner sc = new Scanner[System.in];

        Map map

            = new HashMap[];

        System.out.println["Enter No of Students"];

        int noOfStudents = Integer.parseInt[sc.nextLine[]];

        for [int i = 0; i < noOfStudents; i++] {

            String input = sc.nextLine[];

            String[] studentdata = input.split[" "];

            String rollno = studentdata[0];

            String name = studentdata[1];

            map.put[rollno, name];

        }

        List ListofKeys = null;

        List ListofValues = null;

        ListofKeys = map.keySet[].stream[].collect[

            Collectors.toCollection[ArrayList::new]];

        ListofValues = map.values[].stream[].collect[

            Collectors.toCollection[ArrayList::new]];

        System.out.println["List of RollNo of Students"];

        System.out.println[ListofKeys.toString[]];

        System.out.println["List of Name of Students"];

        System.out.println[ListofValues.toString[]];

    }

}

Output:


By Arvind Rai, September 23, 2016

On this page we will provide java 8 convert Map to List using Collectors.toList[] example. A Map has key and value and we can get all keys and values as List. If we want to set key and value in a class attribute and then add the object into List, we can achieve it in single line of code of java 8 using Collectors.toList[]. Now let us see how to do it. Contents To convert Map to List with lambda expression using Collectors.toList[] is as follows.

List valueList = map.values[].stream[].collect[Collectors.toList[]];

If we want to sort the values before putting into List, we do it as follows.

List sortedValueList = map.values[].stream[] .sorted[].collect[Collectors.toList[]];

We can also convert Map to List of user object with given Comparator using Comparator.comparing[].

List list = map.entrySet[].stream[].sorted[Comparator.comparing[e -> e.getKey[]]] .map[e -> new Person[e.getKey[], e.getValue[]]].collect[Collectors.toList[]];

Here Person is a user class. We can also use Map.Entry to get Map value and key as follows.

List list = map.entrySet[].stream[].sorted[Comparator.comparing[Map.Entry::getValue]] .map[e -> new Person[e.getKey[], e.getValue[]]].collect[Collectors.toList[]];

For comparison, we can also use Map.Entry.comparingByValue[] and Map.Entry.comparingByKey[] to sort the data on the basis of value and key respectively.

List list = map.entrySet[].stream[].sorted[Map.Entry.comparingByKey[]] .map[e -> new Person[e.getKey[], e.getValue[]]].collect[Collectors.toList[]];



SimpleMapToList.java

package com.concretepage; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class SimpleMapToList { public static void main[String[] args] { Map map = new HashMap[]; map.put[23, "Mahesh"]; map.put[10, "Suresh"]; map.put[26, "Dinesh"]; map.put[11, "Kamlesh"]; System.out.println["--Convert Map Values to List--"]; List valueList = map.values[].stream[].collect[Collectors.toList[]]; valueList.forEach[n -> System.out.println[n]]; System.out.println["--Convert Map Values to List using sort--"]; List sortedValueList = map.values[].stream[] .sorted[].collect[Collectors.toList[]]; sortedValueList.forEach[n -> System.out.println[n]]; System.out.println["--Convert Map keys to List--"]; List keyList = map.keySet[].stream[].collect[Collectors.toList[]]; keyList.forEach[n -> System.out.println[n]]; System.out.println["--Convert Map keys to List using sort--"]; List sortedKeyList = map.keySet[].stream[] .sorted[].collect[Collectors.toList[]]; sortedKeyList.forEach[n -> System.out.println[n]]; } }

Output

--Convert Map Values to List-- Mahesh Suresh Dinesh Kamlesh --Convert Map Values to List using sort-- Dinesh Kamlesh Mahesh Suresh --Convert Map keys to List-- 23 10 26 11 --Convert Map keys to List using sort-- 10 11 23 26


MapToListOfUserObject

package com.concretepage; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class MapToListOfUserObject { public static void main[String[] args] { Map map = new HashMap[]; map.put[23, "Mahesh"]; map.put[10, "Suresh"]; map.put[26, "Dinesh"]; map.put[11, "Kamlesh"]; List list = map.entrySet[].stream[].sorted[Comparator.comparing[e -> e.getKey[]]] .map[e -> new Person[e.getKey[], e.getValue[]]].collect[Collectors.toList[]]; list.forEach[l -> System.out.println["Id: "+ l.getId[]+", Name: "+ l.getName[]]]; } }

Person.java

package com.concretepage; public class Person { private Integer id; private String name; public Person[Integer id, String name] { this.id = id; this.name = name; } public Integer getId[] { return id; } public String getName[] { return name; } }

Output

Id: 10, Name: Suresh Id: 11, Name: Kamlesh Id: 23, Name: Mahesh Id: 26, Name: Dinesh

Here the list has been sorted by Map key and if we want to sort it by value, we need to use
Comparator.comparing[e -> e.getValue[]]
and then output will be as follows.

Id: 26, Name: Dinesh Id: 11, Name: Kamlesh Id: 23, Name: Mahesh Id: 10, Name: Suresh

POSTED BY

Video liên quan

Chủ Đề