📜  Java映射到列表的转换

📅  最后修改于: 2022-05-13 01:55:50.944000             🧑  作者: Mango

Java映射到列表的转换

Map 是将键映射到值的对象,或者是属性-值对的集合。列表是对象的有序集合,并且列表可以包含重复值。 Map 有两个值(键和值),而 List 只有一个值(元素)。所以我们可以生成两个列表:

  • 值列表和
  • 地图中的键列表。

让我们假设“ map”是 Map 的实例,此后我们都知道它包含集合和值对。所以它们定义如下:

  • map.values()将返回地图值的集合。
  • map.keySet()将返回一组地图的键。

方法:

  1. 在 ArrayList 构造函数参数中传递键集
  2. 将 map.values() 方法生成的地图值集合传递给 ArrayList 构造函数参数
  3. 使用 Streams API(仅适用于 JDK 8 及更高版本)

让我们讨论它们中的每一个

方法 1:在 ArrayList 构造函数参数中传递键集

过程:我们可以绕过map.keySet()方法生成的映射键集合到ArrayList构造函数参数,将映射键转换为键列表,如下所示

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. 

语法:此后如下:

List ListofKeys = new ArrayList(map.keySet());

方法二: ListListofKeys = new ArrayList(map.keySet());

我们可以通过将map.values() 方法生成的映射值集合传递给 ArrayList 构造函数参数,将映射键转换为值列表。

语法:此后如下:

List Listofvalues = new ArrayList(map.values());

例子

Java
// Java Program to Convert Map to List
 
// Importing required classes
import java.util.*;
 
class GFG {
 
    // Method 1
    public static void main(String[] args)
    {
 
        // Creating HashMap
        HashMap hs = new HashMap<>();
 
        // Adding elements to 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);
 
        // Calling method
        MapValuesToList obj = new MapValuesToList(hs);
 
        // Storing into List
        List mapvaltolist = obj.mapvaltolist(hs);
 
        // Printing via for loops
        for (Integer integerList : mapvaltolist) {
 
            // Printing our ArrayList
            System.out.println(integerList);
        }
    }
 
    // Method 2
    // To convert Map to List
    public List
    mapvaltolist(Map map)
    {
 
        // Using Collection
        Collection val = map.values();
 
        // Creating an ArrayList
        ArrayList al = new ArrayList<>(values);
 
        return al;
    }
}


Java
// Java program to Convert Map to List
 
// Importing required classes
import java.util.*;
// Importing stream sub-package
import java.util.stream.*;
 
// Main class
// MapToList
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Scanner class to take input of key-value pairs
        Scanner sc = new Scanner(System.in);
 
        // Creating a Hashmap which maps rollno with student
        // name
        Map map
            = new HashMap();
 
        // Command for better usability
        System.out.println("Enter No of Students");
 
        // Taking input to Hashmap
        // via iterating using for loop
        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];
 
            // Simply inserting received pairs to Map
            map.put(rollno, name);
        }
 
        // Now first create list of keys and values
        List ListofKeys = null;
        List ListofValues = null;
 
        // Now converting hashMap to List of keys and values
        ListofKeys = map.keySet().stream().collect(
            Collectors.toCollection(ArrayList::new));
        ListofValues = map.values().stream().collect(
            Collectors.toCollection(ArrayList::new));
 
        // lastly printing List of rollno and name of
        // students
        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());
    }
}


输出:

1
2
3
4
5
6

方法 3:使用 Streams API

stream() 方法从 Map.keySet() 返回的映射键集合中返回键流。 Stream 类的 collect() 方法收集 List 中的键流。将 Collectors.toCollection(ArrayList::new) 传递给 collect() 方法以收集为新的 ArrayList。还可以使用 Stream API 将映射键和值转换为相应的列表。语法如下所示:

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

执行:

给定 RollNo 和 N 个学生的学生姓名作为输入。首先,我们创建一个 Map,其中 Rollno 是键,因为 Rollno 是唯一的,并且 Name 作为 Map 的值,然后将此映射分别转换为值和键的列表。其中,生成的键列表包含学生的 RollNo,值的列表包含学生的姓名。

例子

Java

// Java program to Convert Map to List
 
// Importing required classes
import java.util.*;
// Importing stream sub-package
import java.util.stream.*;
 
// Main class
// MapToList
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Scanner class to take input of key-value pairs
        Scanner sc = new Scanner(System.in);
 
        // Creating a Hashmap which maps rollno with student
        // name
        Map map
            = new HashMap();
 
        // Command for better usability
        System.out.println("Enter No of Students");
 
        // Taking input to Hashmap
        // via iterating using for loop
        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];
 
            // Simply inserting received pairs to Map
            map.put(rollno, name);
        }
 
        // Now first create list of keys and values
        List ListofKeys = null;
        List ListofValues = null;
 
        // Now converting hashMap to List of keys and values
        ListofKeys = map.keySet().stream().collect(
            Collectors.toCollection(ArrayList::new));
        ListofValues = map.values().stream().collect(
            Collectors.toCollection(ArrayList::new));
 
        // lastly printing List of rollno and name of
        // students
        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());
    }
}

输出: