filter

使用Stream的filter进行过滤,只保留男性的操作:

  1. Collection<Person> collection = new ArrayList();
  2. collection.add(new Person("张三", 22, "男"));
  3. collection.add(new Person("李四", 19, "女"));
  4. collection.add(new Person("王五", 34, "男"));
  5. collection.add(new Person("赵六", 30, "男"));
  6. collection.add(new Person("田七", 25, "女"));
  7. Stream<Person> personStream = collection.stream().filter(new Predicate<Person>() {
  8. @Override
  9. public boolean test(Person person) {
  10. return "男".equals(person.getGender());//只保留男性
  11. }
  12. });
  13. collection = personStream.collect(Collectors.toList());//将Stream转化为List
  14. System.out.println(collection.toString());//查看结果