Java 8 - List 转 Map

文章目录

List to Map

实体类:

public class Type {

    private Integer id;
    private String name;

    // 略:Getter、Setter、toString
}

测试类:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Test {
    
    public static void main(String[] args) {
        List<Type> types = new ArrayList<>();

        types.add(new Type(1, "Java"));
        types.add(new Type(2, "MySQL"));
        types.add(new Type(3, "Spring"));
        
        Function<? super Type, ? extends Integer> keyMapper = Type::getId;
        Function<? super Type, ? extends Type> valueMapper = type -> type;
//        System.out.println(keyMapper);
//        System.out.println(valueMapper);
        
        Map<Integer, Type> map = types.stream().collect(Collectors.toMap(keyMapper, valueMapper));
        System.out.println(map);
        Set<Integer> keys = map.keySet();
        for (Integer key : keys) {
            System.out.println(map.get(key));
        }
    }
}

控制台输出:

{1=Type [id=1, name=Java], 2=Type [id=2, name=MySQL], 3=Type [id=3, name=Spring]}
Type [id=1, name=Java]
Type [id=2, name=MySQL]
Type [id=3, name=Spring]

参考

Java8中list转map方法总结

Java 8 中的 Streams API 详解

发布了55 篇原创文章 · 获赞 0 · 访问量 3177

猜你喜欢

转载自blog.csdn.net/qq_29761395/article/details/104203442