lambda -- 获取集合中某个属性的所有值

代码块

GetElementFromList.java

package com.example.demo.util;

import com.example.demo.entity.UserPO;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class GetElementFromList {
    public static void main(String[] args) {
        //1. 初始化数据
        UserPO user1 = new UserPO(1, "java");
        UserPO user2 = new UserPO(2, "C");
        UserPO user3 = new UserPO(3, "PHP");
        List<UserPO> users = new ArrayList<>();
        users.add(user1);
        users.add(user2);
        users.add(user3);

        //2. 获取list集合中的某个元素
        List<Integer> ids = users.stream().map(user -> user.getId()).collect(Collectors.toList());

        //3. 遍历
        ids.forEach(System.out::println);
    }
}

UserPO.java

package com.example.demo.entity;

public class UserPO {
    private Integer id;
    private String name;

    public UserPO(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

输出

1
2
3

你可能感兴趣的:(java)