List<属性值类型> 属性List = 对象List.stream().map(对象::get方法()).collect(Collectors.toList());
例如:
List<Integer> idList = list.stream().map(User::getId).collect(Collectors.toList()); //或者 List<Integer> idList = list.stream().map(u -> u.getId()).collect(Collectors.toList());
举例
public class HelloWorld { public static void main(String[] args) { List<User> list = new ArrayList<>(); for(int i=1;i<=10;i++) { User u = new User(i, "用户-" + i); list.add(u); } //取出id列表 //List<Integer> idList = list.stream().map(User::getId).collect(Collectors.toList()); List<Integer> idList = list.stream().map(u -> u.getId()).collect(Collectors.toList()); System.out.println("id列表:" + idList); } private static class User{ int id; String name; public User(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int 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 + '/'' + '}'; } } }
执行后:
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/16949.html