当前位置:网站首页>List to map (split the list according to the key, and the value of the same key is a list)

List to map (split the list according to the key, and the value of the same key is a list)

2020-11-06 21:45:31 Architects who can drive

/**
 * @description  according to key Split list
 * @data ${DATA}
 * @auther
 */
public class MyListTOMap {

    public static void main(String[] args) {
        UserTest user1 = new UserTest(10,"xiaoming");
        UserTest user2 = new UserTest(20,"zhongming");
        UserTest user3 = new UserTest(30,"daming");
        UserTest user4 = new UserTest(30,"i'mgoal");
        List<UserTest> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);
        Map<Integer,List<UserTest>> mapTest = new HashMap<>();
        for (UserTest u: list) {
            if(mapTest.containsKey(u.getAge())){
                mapTest.get(u.getAge()).add(u);
            }else{
                List<UserTest> tempList = new ArrayList<>();
                tempList.add(u);
                mapTest.put(u.getAge(),tempList);
            }
        }
        list.forEach(System.out::println);
        System.out.println(mapTest);
    }
}

版权声明
本文为[Architects who can drive]所创,转载请带上原文链接,感谢