假設有一個員工對象:
<b>public</b> <b>class</b> Employee { <font><i>// member variables</i></font><font> <b>private</b> <b>int</b> empId; <b>private</b> String empName; <b>private</b> <b>int</b> empAge; <b>private</b> String empDesignation;</font>
將這個員工對象放入LIst集合,如何轉為Map? 首先要明確Map的key是什么?
1. 比如式樣員工對象的empId作為key,值是員工姓名:
<font><i>// convert List<Employee> to Map<empId, empName> using Java 8 Streams</i></font><font> Map<Integer, String> mapOfEmployees = employees.stream().collect( Collectors.toMap(e -> e.getEmpId(),e -> e.getEmpName()));</font>
2.Map的Key是empId,整個對象為Map的值:
<font><i>// convert List<Employee> to Map<empId, empName> using Java 8 Streams</i></font><font>Map<Integer, Employee> mapOfEmployees = employees.stream().collect( Collectors.toMap( e -> e.getEmpId(), e -> e));</font>
3. 如果List中有重復的empId,映射到Map時,Key時不能重復的,如何解決?
默認情況時會拋重復異常,為了克服IllegalStateException重復鍵異常,我們可以簡單地添加一個
BinaryOperator方法到toMap()中,這也稱為合并功能,比如如果重復,可以取第一個元素:
Map<Integer, String> mapOfEmployees = employees.stream().collect( Collectors.toMap( e -> e.getEmpId(), e -> e.getEmpName(), (e1, e2) -> e1 )); <font><i>// Merge Function</i></font><font></font>
4. 將List轉換為Map - 使用TreeMap對鍵進行自然排序,或者指定的Map實現呢?
Map<Integer, String> mapOfEmployees = employees.stream().collect( Collectors.toMap( e -> e.getEmpId(), e -> e.getEmpName(), (e1, e2) -> e1 , <font><i>// Merge Function</i></font><font> TreeMap<Integer, String>::<b>new</b>)); </font><font><i>// Map Supplier</i></font><font></font>
如果你的TreeMap實現需要加入比較器,將上面代碼中TreeMap<Integer, String>::
new替換成:
() -> new TreeMap<Integer, String>(new MyComparator())
總結
以上所述是小編給大家介紹的在Java 8中將List轉換為Map對象方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網網站的支持!
新聞熱點
疑難解答
圖片精選