好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

在Java 8中将List转换为Map对象方法

假设有一个员工对象:

?

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集合,如何转为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中有重复的empid,映射到map时,key时不能重复的,如何解决?

默认情况时会抛重复异常,为了克服illegalstateexception重复键异常,我们可以简单地添加一个

binaryoperator方法到tomap()中,这也称为合并功能,比如如果重复,可以取第一个元素:

?

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转换为map - 使用treemap对键进行自然排序,或者指定的map实现呢?

?

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实现需要加入比较器,将上面代码中 treemap<integer, string>:: new替换成:

?

1

() -> new treemap<integer, string>( new mycomparator())

总结

以上所述是小编给大家介绍的在java 8中将list转换为map对象方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

原文链接:https://www.jdon.com/50731

查看更多关于在Java 8中将List转换为Map对象方法的详细内容...

  阅读:17次