假设有一个员工对象:
public class Employee {
// member variablesprivate int empId;
private String empName;
private int empAge;
private String empDesignation;
将这个员工对象放入LIst集合,如何转为Map? 首先要明确Map的key是什么?
1. 比如式样员工对象的empId作为key,值是员工姓名:
// convert List to Map using Java 8 StreamsMap mapOfEmployees = employees.stream().collect(
Collectors.toMap(e -> e.getEmpId(),e -> e.getEmpName()));
2.Map的Key是empId,整个对象为Map的值:
// convert List to Map using Java 8 StreamsMap mapOfEmployees = employees.stream().collect(
Collectors.toMap( e -> e.getEmpId(), e -> e));
3. 如果List中有重复的empId,映射到Map时,Key时不能重复的,如何解决?
默认情况时会抛重复异常,为了克服IllegalStateException重复键异常,我们可以简单地添加一个BinaryOperator方法到toMap()中,这也称为合并功能,比如如果重复,可以取第一个元素:
Map mapOfEmployees = employees.stream().collect(
Collectors.toMap(
e -> e.getEmpId(),
e -> e.getEmpName(),
(e1, e2) -> e1 )); // Merge Function
4. 将List转换为Map - 使用TreeMap对键进行自然排序,或者指定的Map实现呢?
Map mapOfEmployees = employees.stream().collect(
Collectors.toMap(
e -> e.getEmpId(),
e -> e.getEmpName(),
(e1, e2) -> e1 , // Merge FunctionTreeMap::new));// Map Supplier
如果你的TreeMap实现需要加入比较器,将上面代码中TreeMap::new替换成:
() -> new TreeMap(new MyComparator())