Java 8 - List turn Map

Article Directory

List to Map

Entity classes:

public class Type {

    private Integer id;
    private String name;

    // 略:Getter、Setter、toString
}

Test categories:

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

Console output:

{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]

reference

Java8 in turn map list Methods

Java Streams API 8 Comments

Published 55 original articles · won praise 0 · Views 3177

Guess you like

Origin blog.csdn.net/qq_29761395/article/details/104203442