假設(shè)有一個員工對象:
1
2
3
4
5
6
7
|
<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集合,如何轉(zhuǎn)為map? 首先要明確map的key是什么?
1. 比如式樣員工對象的empid作為key,值是員工姓名:
1
2
3
4
|
<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的值:
1
2
3
4
|
<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中有重復(fù)的empid,映射到map時,key時不能重復(fù)的,如何解決?
默認(rèn)情況時會拋重復(fù)異常,為了克服illegalstateexception重復(fù)鍵異常,我們可以簡單地添加一個
binaryoperator方法到tomap()中,這也稱為合并功能,比如如果重復(fù),可以取第一個元素:
1
2
3
4
5
6
|
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轉(zhuǎn)換為map - 使用treemap對鍵進(jìn)行自然排序,或者指定的map實現(xiàn)呢?
1
2
3
4
5
6
7
|
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實現(xiàn)需要加入比較器,將上面代碼中treemap<integer, string>::
new替換成:
1
|
() -> new treemap<integer, string>( new mycomparator()) |
總結(jié)
以上所述是小編給大家介紹的在java 8中將list轉(zhuǎn)換為map對象方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
原文鏈接:https://www.jdon.com/50731