java8 将List转换为Map

参考: http://www.mkyong.com/java8/java-8-convert-list-to-map/

1 准备数据

Employee对象:

package com.tao.springstarter.entity;

public class Employee {

    /** * 姓名 */
    private String name;

    /** * 年龄 */
    private Integer age;

    /** * 所在城市 */
    private String city;

    /** * 销售额 */
    private Double sales;

    public Employee(String name, Integer age, String city, Double sales) {
        this.name = name;
        this.age = age;
        this.city = city;
        this.sales = sales;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Double getSales() {
        return sales;
    }

    public void setSales(Double sales) {
        this.sales = sales;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", city='" + city + '\'' +
                ", sales=" + sales +
                '}';
    }
}

List<Employee>对象:

	List<Employee> employeeList = new ArrayList<>();
	employeeList.add(new Employee("Alice", 23, "London", 1200.00));
	employeeList.add(new Employee("Bob", 19, "London", 2000.00));
	employeeList.add(new Employee("Charles", 25, "New York", 1650.00));
	employeeList.add(new Employee("Dorothy", 20, "Hong Kong", 1200.00));

2 ListMap

2.1 Collectors.toMap函数说明

ListMap 通常使用 Collectors.toMap 函数进行转换。在Collectors中,toMap总共有三种形态:

2.1.1 第一种

    public static <T, K, U>
    Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                    Function<? super T, ? extends U> valueMapper) {
        return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
    }

其中,

  • keyMapper —— 指定map中的键的获取方法。
  • valueMapper —— 指定map中的值的获取方法。
  • 默认使用HashMapMap的实现类,当键值相同发生冲突时,抛出异常。

栗子:

(1)

	// key - name, value - Employee
	Map<String, Employee> map1 = employeeList.stream()
				.collect(toMap(Employee::getName, Function.identity()));

(2)

	// key - name, value - age
	Map<String, Integer> map2 = employeeList.stream()
                .collect(toMap(Employee::getName, Employee::getAge));

2.1.2 第二种(提供解决key冲突的策略)

    public static <T, K, U>
    Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                    Function<? super T, ? extends U> valueMapper,
                                    BinaryOperator<U> mergeFunction) {
        return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
    }

其中,

  • keyMapper —— 指定map中的键的获取方法。
  • valueMapper —— 指定map中的值的获取方法。
  • mergeFunction —— 指定key冲突时,保存value的策略。
  • 默认使用HashMapMap的实现类。

栗子:

(1)key冲突时,舍弃value的旧值,使用value的新值。

	// key - city, value - name
	Map<String, String> map3 = employeeList.stream()
                .collect(toMap(Employee::getCity, Employee::getName, (oldValue, newValue) -> newValue));

2.1.3 第三种(提供指定Map实现类的策略)

    public static <T, K, U, M extends Map<K, U>>
    Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
                                Function<? super T, ? extends U> valueMapper,
                                BinaryOperator<U> mergeFunction,
                                Supplier<M> mapSupplier) {
        BiConsumer<M, T> accumulator
                = (map, element) -> map.merge(keyMapper.apply(element),
                                              valueMapper.apply(element), mergeFunction);
        return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);
    }

其中,

  • keyMapper —— 指定map中的键的获取方法。
  • valueMapper —— 指定map中的值的获取方法。
  • mergeFunction —— 指定key冲突时,保存value的策略。
  • mapSupplier —— 指定Map的实现类。

栗子:

(1)使用LinkedHashMapMap的实现类

	// key - city, value - name, use LinkedHashMap
	Map<String, String> map4 = employeeList.stream()
                .collect(toMap(Employee::getCity, Employee::getName, (oldValue, newValue) -> newValue, LinkedHashMap::new));
    原文作者:牧_风
    原文地址: https://blog.csdn.net/hbtj_1216/article/details/84539302
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞