如何在Java 8中将List转换为Map?

栏目: 编程语言 · Java · 发布时间: 7年前

内容简介:假设有一个员工对象:将这个员工对象放入LIst集合,如何转为Map? 首先要明确Map的key是什么?1. 比如式样员工对象的empId作为key,值是员工姓名:

假设有一个员工对象:

<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?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

SCWCD Exam Study Kit Second Edition

SCWCD Exam Study Kit Second Edition

Hanumant Deshmukh、Jignesh Malavia、Matthew Scarpino / Manning Publications / 2005-05-20 / USD 49.95

Aimed at helping Java developers, Servlet/JSP developers, and J2EE developers pass the Sun Certified Web Component Developer Exam (SCWCD 310-081), this study guide covers all aspects of the Servlet an......一起来看看 《SCWCD Exam Study Kit Second Edition》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具