當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java List轉Map用法及代碼示例


List 是 Collection 的子接口。它是一個有序的對象集合,其中可以存儲重複的值。由於 List 保留插入順序,因此它允許位置訪問和插入元素。列表接口由 ArrayListLinkedListVectorStack 類實現。

Map接口表示鍵和值之間的映射。 Map 接口不是 Map 接口的子類型集合接口。因此它的行為與其他集合類型有點不同。
mapinterface

例子:

Input: List : [1="1", 2="2", 3="3"]
Output: Map : {1=1, 2=2, 3=3}

Input: List : [1="Geeks", 2="for", 3="Geeks"]
Output: Map : {1=Geeks, 2=for, 3=Geeks}

下麵是在 Java 中將 List 轉換為 Map 的多種方法。為此,假設 List 的每個元素都有一個標識符,該標識符將用作結果 Map 中的鍵。

  1. 按列表對象使用:

    方法:

    1. 獲取要轉換為Map的List
    2. 創建一個空Map
    3. 迭代列表中的項目並將每個項目添加到 Map 中。
    4. 返回形成的Map
    
    // Java program for list convert in map 
    // with the help of Object method 
      
    import java.util.ArrayList; 
    import java.util.List; 
    import java.util.Map; 
    import java.util.HashMap; 
      
    // create a list 
    class Student { 
      
        // id will act as Key 
        private Integer id; 
      
        // name will act as value 
        private String name; 
      
        // create curstuctor for reference 
        public Student(Integer id, String name) 
        { 
      
            // assign the value of id and name 
            this.id = id; 
            this.name = name; 
        } 
      
        // return private variable id 
        public Integer getId() 
        { 
            return id; 
        } 
      
        // return private variable name 
        public String getName() 
        { 
            return name; 
        } 
    } 
      
    // main class and method 
    public class GFG { 
      
        // main Driver 
        public static void main(String[] args) 
        { 
      
            // create a list 
            List<Student> 
                lt = new ArrayList<Student>(); 
      
            // add the member of list 
            lt.add(new Student(1, "Geeks")); 
            lt.add(new Student(2, "For")); 
            lt.add(new Student(3, "Geeks")); 
      
            // create map with the help of 
            // Object (stu) method 
            // create object of Map class 
            Map<Integer, String> map = new HashMap<>(); 
      
            // put every value list to Map 
            for (Student stu : lt) { 
                map.put(stu.getId(), stu.getName()); 
            } 
      
            // print map 
            System.out.println("Map  : " + map); 
        } 
    } 
    輸出:
    Map  : {1=Geeks, 2=For, 3=Geeks}
    
  2. 使用 Collectors.toMap() 方法:此方法包括創建學生對象列表,並使用 Collectors.toMap() 將其轉換為 Map。
    Approach:
    1. 獲取要轉換為Map的List
    2. 使用List.stream()方法將List轉換為流
    3. 借助 Collectors.toMap() 方法創建Map
    4. 使用stream.collect()方法收集形成的Map
    5. 返回形成的Map
    
    // Java program for list convert  in map 
    // with the help of Collectors.toMap() method 
      
    import java.util.ArrayList; 
    import java.util.LinkedHashMap; 
    import java.util.List; 
    import java.util.stream.Collectors; 
      
    // create a list 
    class Student { 
      
        // id will act as Key 
        private Integer id; 
      
        // name will act as value 
        private String name; 
      
        // create curstuctor for reference 
        public Student(Integer id, String name) 
        { 
      
            // assign the value of id and name 
            this.id = id; 
            this.name = name; 
        } 
      
        // return private variable id 
        public Integer getId() 
        { 
            return id; 
        } 
      
        // return private variable name 
        public String getName() 
        { 
            return name; 
        } 
    } 
      
    // main class and method 
    public class GFG { 
      
        // main Driver 
        public static void main(String[] args) 
        { 
      
            // create a list 
            List<Student> lt = new ArrayList<>(); 
      
            // add the member of list 
            lt.add(new Student(1, "Geeks")); 
            lt.add(new Student(2, "For")); 
            lt.add(new Student(3, "Geeks")); 
      
            // create map with the help of 
            // Collectors.toMap() method 
            LinkedHashMap<Integer, String> 
                map = lt.stream() 
                          .collect( 
                              Collectors 
                                  .toMap( 
                                      Student::getId, 
                                      Student::getName, 
                                      (x, y) 
                                          -> x + ", " + y, 
                                      LinkedHashMap::new)); 
      
            // print map 
            map.forEach( 
                (x, y) -> System.out.println(x + "=" + y)); 
        } 
    } 
    輸出:
    1=Geeks
    2=For
    3=Geeks
    
  3. 使用Collector創建MultiMap。groupingBy():

    方法:

    1. 獲取要轉換為Map的List
    2. 使用List.stream()方法將List轉換為流
    3. 借助 Collectors.groupingBy() 方法創建Map
    4. 使用stream.collect()方法收集形成的Map
    5. 返回形成的Map
    
    // Java program for list convert  in map 
    // with the help of Collectors.groupingBy() method 
      
    import java.util.*; 
    import java.util.stream.Collectors; 
      
    // create a list 
    class Student { 
      
        // id will act as Key 
        private Integer id; 
      
        // name will act as value 
        private String name; 
      
        // create curstuctor for reference 
        public Student(Integer id, String name) 
        { 
      
            // assign the value of id and name 
            this.id = id; 
            this.name = name; 
        } 
      
        // return private variable id 
        public Integer getId() 
        { 
            return id; 
        } 
      
        // return private variable name 
        public String getName() 
        { 
            return name; 
        } 
    } 
      
    // main class and method 
    public class GFG { 
      
        // main Driver 
        public static void main(String[] args) 
        { 
      
            // create a list 
            List<Student> lt = new ArrayList<Student>(); 
      
            // add the member of list 
            lt.add(new Student(1, "Geeks")); 
            lt.add(new Student(1, "For")); 
            lt.add(new Student(2, "Geeks")); 
            lt.add(new Student(2, "GeeksForGeeks")); 
      
            // create map with the help of 
            // Object (stu) method 
            // create object of Multi Map class 
      
            // create multimap and store the value of list 
            Map<Integer, List<String> > 
                multimap = lt 
                               .stream() 
                               .collect( 
                                   Collectors 
                                       .groupingBy( 
                                           Student::getId, 
                                           Collectors 
                                               .mapping( 
                                                   Student::getName, 
                                                   Collectors 
                                                       .toList()))); 
      
            // print the multiMap 
            System.out.println("MultiMap = " + multimap); 
        } 
    } 
    輸出:
    MultiMap = {1=[Geeks, For], 2=[Geeks, GeeksForGeeks]}
    


相關用法


注:本文由純淨天空篩選整理自Rajput-Ji大神的英文原創作品 Program to Convert List to Map in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。