当前位置:网站首页>list转换map(根据key来拆分list,相同key的value为一个list)

list转换map(根据key来拆分list,相同key的value为一个list)

2020-11-06 21:45:00 会开车的架构师

/**
 * @description 按照key拆分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);
    }
}

版权声明
本文为[会开车的架构师]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4629483/blog/4529695