之前的Java集合中removeIf的使用一文寫了使用removeIf來實現按條件對集合進行過濾。這篇文章使用同樣是JDK1.8新加入的Stream中filter方法來實現同樣的效果。並且在實際項目中通常使用filter更多。關於Stream的詳細介紹參見Java 8系列之Stream的基本語法詳解。
同樣的場景:你是公司某個崗位的HR,收到了大量的簡歷,為了節約時間,現需按照一點規則過濾一下這些簡歷。比如要經常熬夜加班,所以只招收男性。
//求職者的實體類 public class Person { private String name;//姓名 private Integer age;//年齡 private String gender;//性別 ... //省略構造方法和getter、setter方法 ... //重寫toString,方便觀看結果 @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", gender='" + gender + '\'' + '}'; } }
這里就不展示使用傳統Iterator來進行過濾了,有需要做對比的可以參見之前的Java集合中removeIf的使用。
使用Stream的filter進行過濾,只保留男性的操作:
Collection<Person> collection = new ArrayList(); collection.add(new Person("張三", 22, "男")); collection.add(new Person("李四", 19, "女")); collection.add(new Person("王五", 34, "男")); collection.add(new Person("趙六", 30, "男")); collection.add(new Person("田七", 25, "女")); Stream<Person> personStream = collection.stream().filter(new Predicate<Person>() { @Override public boolean test(Person person) { return "男".equals(person.getGender());//只保留男性 } }); collection = personStream.collect(Collectors.toList());//將Stream轉化為List System.out.println(collection.toString());//查看結果
運行結果如下:
[Person{name=‘張三’, age=22, gender=‘男’}, Person{name=‘王五’, age=34, gender=‘男’}, Person{name=‘趙六’, age=30, gender=‘男’}]
Process finished with exit code 0
上面的demo沒有使用lambda表達式,下面的demo使用lambda來進一步精簡代碼:
Collection<Person> collection = new ArrayList(); collection.add(new Person("張三", 22, "男")); collection.add(new Person("李四", 19, "女")); collection.add(new Person("王五", 34, "男")); collection.add(new Person("趙六", 30, "男")); collection.add(new Person("田七", 25, "女")); Stream<Person> personStream = collection.stream().filter( person -> "男".equals(person.getGender())//只保留男性 ); collection = personStream.collect(Collectors.toList());//將Stream轉化為List System.out.println(collection.toString());//查看結果
效果和不用lambda是一樣的。
不過讀者在使用filter時不要和removeIf弄混淆了:
removeIf中的test方法返回true代表當前元素會被過濾掉;filter中的test方法返回true代表當前元素會保留下來。
