java 8中 predicate chain的使用
文章目錄
- 簡介
- 基本使用
- 使用多個Filter
- 使用復合Predicate
- 組合Predicate
- Predicate的集合操作
- 總結
java 8中 predicate chain的使用
簡介
Predicate是一個FunctionalInterface,代表的方法需要輸入一個參數,返回boolean類型。通常用在stream的filter中,表示是否滿足過濾條件。
boolean test(T t);基本使用
我們先看下在stream的filter中怎么使用Predicate:
@Testpublic void basicUsage(){List<String> stringList=Stream.of("a","b","c","d").filter(s -> s.startsWith("a")).collect(Collectors.toList());log.info("{}",stringList);}上面的例子很基礎了,這里就不多講了。
使用多個Filter
如果我們有多個Predicate條件,則可以使用多個filter來進行過濾:
public void multipleFilters(){List<String> stringList=Stream.of("a","ab","aac","ad").filter(s -> s.startsWith("a")).filter(s -> s.length()>1).collect(Collectors.toList());log.info("{}",stringList);}上面的例子中,我們又添加了一個filter,在filter又添加了一個Predicate。
使用復合Predicate
Predicate的定義是輸入一個參數,返回boolean值,那么如果有多個測試條件,我們可以將其合并成一個test方法:
@Testpublic void complexPredicate(){List<String> stringList=Stream.of("a","ab","aac","ad").filter(s -> s.startsWith("a") && s.length()>1).collect(Collectors.toList());log.info("{}",stringList);}上面的例子中,我們把s.startsWith(“a”) && s.length()>1 作為test的實現。
組合Predicate
Predicate雖然是一個interface,但是它有幾個默認的方法可以用來實現Predicate之間的組合操作。
比如:Predicate.and(), Predicate.or(), 和 Predicate.negate()。
下面看下他們的例子:
@Testpublic void combiningPredicate(){Predicate<String> predicate1 = s -> s.startsWith("a");Predicate<String> predicate2 = s -> s.length() > 1;List<String> stringList1 = Stream.of("a","ab","aac","ad").filter(predicate1.and(predicate2)).collect(Collectors.toList());log.info("{}",stringList1);List<String> stringList2 = Stream.of("a","ab","aac","ad").filter(predicate1.or(predicate2)).collect(Collectors.toList());log.info("{}",stringList2);List<String> stringList3 = Stream.of("a","ab","aac","ad").filter(predicate1.or(predicate2.negate())).collect(Collectors.toList());log.info("{}",stringList3);}實際上,我們并不需要顯示的assign一個predicate,只要是滿足
predicate接口的lambda表達式都可以看做是一個predicate。同樣可以調用and,or和negate操作:
Predicate的集合操作
如果我們有一個Predicate集合,我們可以使用reduce方法來對其進行合并運算:
@Testpublic void combiningPredicateCollection(){List<Predicate<String>> allPredicates = new ArrayList<>();allPredicates.add(a -> a.startsWith("a"));allPredicates.add(a -> a.length() > 1);List<String> stringList = Stream.of("a","ab","aac","ad").filter(allPredicates.stream().reduce(x->true, Predicate::and)).collect(Collectors.toList());log.info("{}",stringList);}上面的例子中,我們調用reduce方法,對集合中的Predicate進行了and操作。
總結
本文介紹了多種Predicate的操作,希望大家在實際工作中靈活應用。
本文的例子https://github.com/ddean2009/learn-java-streams/tree/master/predicate-chain
更多精彩內容且看:
- 區塊鏈從入門到放棄系列教程-涵蓋密碼學,超級賬本,以太坊,Libra,比特幣等持續更新
- Spring Boot 2.X系列教程:七天從無到有掌握Spring Boot-持續更新
- Spring 5.X系列教程:滿足你對Spring5的一切想象-持續更新
- java程序員從小工到專家成神之路(2020版)-持續更新中,附詳細文章教程
歡迎關注我的公眾號:程序那些事,更多精彩等著您!
更多內容請訪問 www.flydean.com
總結
以上是生活随笔為你收集整理的java 8中 predicate chain的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JDK 14的新特性:更加好用的Null
- 下一篇: java 8中构建无限的stream