Java8使List转为Map

2022-12-16 14:43:39 浏览数 (1)

Java8使List转为Map

代码语言:javascript复制
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));
    }
}

0 人点赞