欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

list stream:List转Map

程序员文章站 2022-07-15 11:59:05
...

List中部分字段转Map

public static void main(String[] args) {
        List<TestUser> userList = new ArrayList();

        TestUser one = new TestUser();
        one.setId(1);
        one.setName("这是老大");
        one.setAge(10D);

        TestUser two = new TestUser();
        two.setId(2);
        two.setName("这是老二");
        two.setAge(8.7);

        TestUser three = new TestUser();
        three.setId(3);
        three.setName("这是老三");
        three.setAge(6.4);



        userList.add(one);
        userList.add(two);
        userList.add(three);
        //转换过程中Map对应的key不重复的情况
        Map<Integer, String> userMap = userList.stream().collect(Collectors.toMap(TestUser::getId, TestUser::getName));
        System.out.println(userMap.toString());

        TestUser four = new TestUser();
        four.setId(3);
        four.setAge(6.8);
        four.setName("这是老三的副本");
        userList.add(four);
        //转换过程中Map对应的key存在重复的情况,需要确定相同时选择的value
        Map<Integer, String> userDuplicateMap = userList.stream().collect(Collectors.toMap(TestUser::getId, TestUser::getName, (oldValue, newValue) -> oldValue));
        System.out.println(userDuplicateMap.toString());
    }

List中对象和字段转Map

public static void main(String[] args) {
        List<TestUser> userList = new ArrayList();

        TestUser one = new TestUser();
        one.setId(1);
        one.setName("这是老大");
        one.setAge(10D);

        TestUser two = new TestUser();
        two.setId(2);
        two.setName("这是老二");
        two.setAge(8.7);

        TestUser three = new TestUser();
        three.setId(3);
        three.setName("这是老三");
        three.setAge(6.4);



        userList.add(one);
        userList.add(two);
        userList.add(three);
        //转换过程中Map对应的key不重复的情况
        Map<Integer, TestUser> userMap = userList.stream().collect(Collectors.toMap(TestUser::getId, TestUser -> TestUser));
        System.out.println(userMap.toString());

        TestUser four = new TestUser();
        four.setId(3);
        four.setAge(6.8);
        four.setName("这是老三的副本");
        userList.add(four);
        //转换过程中Map对应的key存在重复的情况,需要确定相同时选择的value
        Map<Integer, TestUser> userDuplicateMap = userList.stream().collect(Collectors.toMap(TestUser::getId,  TestUser -> TestUser, (oldValue, newValue) -> oldValue));
        System.out.println(userDuplicateMap.toString());
    }