Lambda learning - acquiring a property from the Object List of converting new collection

Copyright Notice: Welcome to reprint: https://blog.csdn.net/u012377333/article/details/88415292

Description of Requirement

Now there is such a demand, there is a collection of user objects, we need to get the user Id converted into a new collection from the inside.

    @Data
    public class User {

        /**
         * 用户Id
         */
        private Integer id;

        /**
         * 姓名
         */
        private String username;

        /**
         * 手机号
         */
        private String phone;
    }

The List <User> userList converted to List <Integer> userIdList

Method to realize

Lambda achieve

    @Test
    public void main() {

        List<User> userList = Lists.newArrayList();
        for (int i = 0; i < 5; i++) {
            User user = new User();
            user.setId(i);
            user.setUsername("user_" + i);
            user.setPhone("1341341349" + i);

            userList.add(user);
        }

        log.info(userList.toString());

        List<Integer> userIds = userList.stream().map(u -> u.getId()).collect(Collectors.toList());

        log.info(userIds.toString());
    }

Output

10:04:51.481 [main] INFO com.csun.cmny.utils.LambdaTest - [LambdaTest.User(id=0, username=user_0, phone=13413413490), LambdaTest.User(id=1, username=user_1, phone=13413413491), LambdaTest.User(id=2, username=user_2, phone=13413413492), LambdaTest.User(id=3, username=user_3, phone=13413413493), LambdaTest.User(id=4, username=user_4, phone=13413413494)]
10:04:51.557 [main] INFO com.csun.cmny.utils.LambdaTest - [0, 1, 2, 3, 4]

Conventional manner

    @Test
    public void test() {

        List<User> userList = Lists.newArrayList();
        for (int i = 5; i < 10; i++) {
            User user = new User();
            user.setId(i);
            user.setUsername("user_" + i);
            user.setPhone("1341341349" + i);

            userList.add(user);
        }

        log.info(userList.toString());

        List<Integer> userIds = Lists.newArrayList();
        for (User user : userList) {
            Integer id = user.getId();
            userIds.add(id);
        }

        log.info(userIds.toString());
    }

Output

10:16:33.884 [main] INFO com.csun.cmny.utils.LambdaTest - [LambdaTest.User(id=5, username=user_5, phone=13413413495), LambdaTest.User(id=6, username=user_6, phone=13413413496), LambdaTest.User(id=7, username=user_7, phone=13413413497), LambdaTest.User(id=8, username=user_8, phone=13413413498), LambdaTest.User(id=9, username=user_9, phone=13413413499)]
10:16:33.888 [main] INFO com.csun.cmny.utils.LambdaTest - [5, 6, 7, 8, 9]

Reference Address: java8 new features: lambda expression: direct access to the field set a list / array / objects inside

Guess you like

Origin blog.csdn.net/u012377333/article/details/88415292