Java: Java8中stream Collectors.toMap将List转为Map

时间:2022-11-30 11:25:45

作用:

  • Collectors.toMap将List转为Map

定义

public final class Collectors {
    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);
    }

    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);
    }

    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);
    }
}

使用示例

定义 User类

package com.github.mouday.demo;

public class User {
    private Integer id;

    private String name;

    private Integer age;

    public User(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

toMap 使用示例

package com.github.mouday.demo;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Demo {
    public static void main(String[] args) {
        List<User> users = Arrays.asList(
                new User(1, "Tom", 20),
                new User(2, "Jack", 30),
                new User(3, "Steve", 40)
        );

        // id作为key, user对象作为value
        // Function.identity() 等价于 t -> t
        Map<Integer, User> collect = users.stream()
                .collect(Collectors.toMap(User::getId, Function.identity()));

        System.out.println(collect);
        // {
        //    1=User{id=1, name='Tom', age=20},
        //    2=User{id=2, name='Jack', age=30},
        //    3=User{id=3, name='Steve', age=40}
        // }

        // id作为key, name作为value
        Map<Integer, String> collect1 = users.stream()
                .collect(Collectors.toMap(User::getId, User::getName));
        System.out.println(collect1);
        // {1=Tom, 2=Jack, 3=Steve}
    }
}

如果key重复,会报错

Exception in thread "main" java.lang.IllegalStateException: 
Duplicate key User{id=1, name='Tom', age=20}

如果key键重复,我们取后者

package com.github.mouday.reggie;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Demo {
    public static void main(String[] args) {
        List<User> users = Arrays.asList(
                new User(1, "Tom", 20),
                new User(2, "Jack", 30),
                new User(3, "Steve", 40),
                new User(1, "Judi", 50)
        );

        // id作为key, user对象作为value
        // Function.identity() 等价于 t -> t
        Map<Integer, User> collect = users.stream()
                .collect(Collectors.toMap(User::getId, Function.identity(), (n1, n2) -> n2));

        System.out.println(collect);
        // {
        // 1=User{id=1, name='Judi', age=50},
        // 2=User{id=2, name='Jack', age=30},
        // 3=User{id=3, name='Steve', age=40}
        // }

        // id作为key, name作为value
        Map<Integer, String> collect1 = users.stream()
                .collect(Collectors.toMap(User::getId, User::getName, (n1, n2) -> n2));
        System.out.println(collect1);
        // {1=Judi, 2=Jack, 3=Steve}
    }


}