List<User> users = new ArrayList<>();
User user = new User();
user.setName("maoliang");
user.setAge(25);
users.add(user);
User user2 = new User();
user2.setName("shaungshuang");
user2.setAge(23);
users.add(user2);
users.forEach(System.out::println);
User(name=maoliang, age=25)
User(name=shaungshuang, age=23)
users.stream().filter(user1 -> user1.getAge() > 24).forEach(System.out::println);
User(name=maoliang, age=25)
Java集合Stream类filter的使用
public static void main(String[] args) throws Exception {
List<User> users = new ArrayList<>();
User user = new User();
user.setName("maoliang");
user.setAge(25);
user.setAge(0);
user.setSex("女");
users.add(user);
User user2 = new User();
user2.setName("shaungshuang");
user2.setAge(23);
user2.setSex("男");
users.add(user2);
User user3 = new User();
user3.setName("asdfasd");
user3.setAge(22);
user3.setSex("男");
users.add(user3);
// 流
Stream<User> userStream = users.stream().filter(new Predicate<User>() {
@Override
public boolean test(User user) {
return "男".equals(user.getSex());// 只保留男性
}
});
users = userStream.collect(Collectors.toList());// 将stream转化为list
users.forEach(System.out::println);
}
输出:
User(name=shaungshuang, age=23, sex=男)
User(name=asdfasd, age=22, sex=男)
lambda
表达式:
// 流
Stream<User> userStream = users.stream().filter(user222-> "男".equals(user222.getSex())); // 只保留男性
users = userStream.collect(Collectors.toList());
System.out.println(users.toString());
输出:
[User(name=shaungshuang, age=23, sex=男), User(name=asdfasd, age=22, sex=男)]
查找集合中的第一个对象:
// 查找集合中的第一个对象
Optional<User> firstUser = users.stream().filter(u -> "shaungshuang".equals(u.getName())).findFirst();
if (firstUser.isPresent()) {
User user1 = firstUser.get();
System.out.println("user1========"+user1);
}
System.out.println("firstUser=========="+firstUser);
如果有,则输出:
user1----------User(name=shaungshuang, age=22, sex=男)
firstUser-------Optional[User(name=shaungshuang, age=22, sex=男)]
如果没有,则输出:
firstUser==========Optional.empty
返回集合:
// 返回集合
List<User> users1 = users.stream().filter(u -> "shaungshang".equals(u.getName())).collect(Collectors.toList());
users1.forEach(System.out::println);
输出:
User(name=shaungshang, age=23, sex=男)
User(name=shaungshang, age=22, sex=男)
抽取对象中所有的name
的集合:
List<String> names = users.stream().map(User::getName).collect(Collectors.toList());
names.forEach(System.out::println);
输出:
maoliang
shaungshang
shaungshang