Java8使List转为Map

简介 在开发中,我们会经常遇到list转map的情况,那么本文就来介绍在JDK1.8下使用lambad表达式来实现list转map

Java8使List转为Map


import com.kaigejava;
 
import javax.jws.soap.SOAPBinding;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
 
public class Main {
 
    public static void main(String[] args) {
 
        List<User> userlist = new ArrayList<>();
        for (int i = 0; i <10; i++) {
 
            userlist.add(new User("张三"+i,i));
        }
        System.out.println(getAllages(userlist).size());
 
        System.out.println(getUser2Map(userlist));
 
        System.out.println(getUser2MapUser(userlist));
 
        System.out.println(getUser2MapUser2(userlist));
 
          System.out.println(getUser2MapUser3(userlist));
 
    }
 
    public static List<Integer> getAllages(List<User>userlist){
        return  userlist.stream().map(user -> user.getAge()).collect(Collectors.toList());
    }
 
    public static Map<Integer,String> getUser2Map(List<User>userlist){
 
        return userlist.stream().collect(Collectors.toMap(User::getAge,User::getName));
    }
 
    public static Map<Integer,User> getUser2MapUser(List<User>userlist){
 
        return userlist.stream().collect(Collectors.toMap(User::getAge,User-> User));
    }
 
    /**
     * 比较优雅的写法是这样的
     * @param userlist
     * @return
     */
    public static Map<Integer,User> getUser2MapUser2(List<User>userlist){
 
        return userlist.stream().collect(Collectors.toMap(User::getAge, Function.identity()));
    }
 
    /**
     * 重复key的情况下 简单的使用后者覆盖前者的
     */
    public static Map<Integer,User> getUser2MapUser3(List<User>userlist){
 
        return userlist.stream().collect(Collectors.toMap(User::getAge, Function.identity(),(key1,key2)->key2));
    }
 
    /**
     *指定map的具体实现
     * @param userlist
     * @return
     */
    public static Map<Integer,User> getUser2MapUser4(List<User>userlist){
 
        return userlist.stream().collect(Collectors.toMap(User::getAge, Function.identity(),(key1,key2)->key2, LinkedHashMap::new));
    }
}


Top Top