Java8中Stream用法总结1
import lombok.Data;
@Data
public class User {
private String name;
private Integer age;
public User(){}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
1. 获取List中对象的某个元素的集合
public List<User> boxedUsers() {
User u1 = new User();
u1.setName("u1");
u1.setAge(18);
User u2 = new User();
u2.setName("u2");
u2.setAge(20);
User u3 = new User();
u3.setName("u3");
u3.setAge(22);
List<User> li = new ArrayList<>();
li.add(u1);
li.add(u2);
li.add(u3);
return li;
}
获取User类中的age属性的集合:
List<Integer> ageLists = users.stream().map(user -> user.getAge()).collect(Collectors.toList());
再将集合排序:
正序:
List<Integer> ageLists = users.stream().map(user -> user.getAge()).sorted(Comparator.comparing(Integer::intValue)).collect(Collectors.toList());
倒序:
List<Integer> ageList = users.stream().map(user -> user.getAge()).sorted(Comparator.comparingInt(Integer::intValue).reversed()).collect(Collectors.toList());