java chain_java 8中 predicate chain的使用
java 8中 predicate chain的使用
簡介
Predicate是一個FunctionalInterface,代表的方法需要輸入一個參數,返回boolean類型。通常用在stream的filter中,表示是否滿足過濾條件。
boolean test(T t);
基本使用
我們先看下在stream的filter中怎么使用Predicate:
@Test
public void basicUsage(){
List 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 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方法:
@Test
public void complexPredicate(){
List 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()。
下面看下他們的例子:
@Test
public void combiningPredicate(){
Predicate predicate1 = s -> s.startsWith("a");
Predicate predicate2 = s -> s.length() > 1;
List stringList1 = Stream.of("a","ab","aac","ad")
.filter(predicate1.and(predicate2))
.collect(Collectors.toList());
log.info("{}",stringList1);
List stringList2 = Stream.of("a","ab","aac","ad")
.filter(predicate1.or(predicate2))
.collect(Collectors.toList());
log.info("{}",stringList2);
List 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操作:
List stringList4 = Stream.of("a","ab","aac","ad")
.filter(((Predicate)a -> a.startsWith("a"))
.and(a -> a.length() > 1))
.collect(Collectors.toList());
log.info("{}",stringList4);
Predicate的集合操作
如果我們有一個Predicate集合,我們可以使用reduce方法來對其進行合并運算:
@Test
public void combiningPredicateCollection(){
List> allPredicates = new ArrayList<>();
allPredicates.add(a -> a.startsWith("a"));
allPredicates.add(a -> a.length() > 1);
List 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的操作,希望大家在實際工作中靈活應用。
歡迎關注我的公眾號:程序那些事,更多精彩等著您!
更多內容請訪問 www.flydean.com
總結
以上是生活随笔為你收集整理的java chain_java 8中 predicate chain的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 医疗:CIS(4)
- 下一篇: 47session 方法