Java 8中提供了Stream API,可以通过该API实现快速高效的对集合对象的转换和处理。下面是提取集合对象的每个属性的完整攻略。
攻略步骤
- 创建集合对象
java
List<User> userList = new ArrayList<>(); - 添加集合元素
java
userList.add(new User("Tom", 20));
userList.add(new User("Lucy", 22));
userList.add(new User("Jerry", 25));
userList.add(new User("Andy", 23)); - 提取集合对象的属性
java
List<String> usernameList = userList.stream().map(User::getUsername).collect(Collectors.toList());
List<Integer> ageList = userList.stream().map(User::getAge).collect(Collectors.toList()); - 获取属性结果
java
System.out.println(usernameList);
System.out.println(ageList);
输出结果为:
[Tom, Lucy, Jerry, Andy]
[20, 22, 25, 23]
示例说明
示例1:提取用户列表中的用户名
public class User {
private String username;
private Integer age;
public User(String username, Integer age) {
this.username = username;
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
userList.add(new User("Tom", 20));
userList.add(new User("Lucy", 22));
userList.add(new User("Jerry", 25));
userList.add(new User("Andy", 23));
List<String> usernameList = userList.stream().map(User::getUsername).collect(Collectors.toList());
System.out.println(usernameList);
}
}
输出结果为:
[Tom, Lucy, Jerry, Andy]
示例2:提取用户列表中的年龄
public class User {
private String username;
private Integer age;
public User(String username, Integer age) {
this.username = username;
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
userList.add(new User("Tom", 20));
userList.add(new User("Lucy", 22));
userList.add(new User("Jerry", 25));
userList.add(new User("Andy", 23));
List<Integer> ageList = userList.stream().map(User::getAge).collect(Collectors.toList());
System.out.println(ageList);
}
}
输出结果为:
[20, 22, 25, 23]
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java8 实现提取集合对象的每个属性 - Python技术站