Java 8谓词(Predicate)链简介说明

书欣 Java经验 发布时间:2022-08-10 11:00:06 阅读数:9779 1
下文笔者讲述java8中Predicate链简介说明,如下所示
使用字母m开头
@Test
public void whenFilterlist_thenSuccess(){
   List<String> names = Arrays.asList("java", "maomao", "xinxiao", "xincheng");
   List<String> result = names.stream()
     .filter(name -> name.startsWith("m"))
     .collect(Collectors.toList());
}

多条件过滤

 
@Test
public void whenFilterListWithMultipleFilters_thenSuccess(){
    List<String> result = names.stream()
      .filter(name -> name.startsWith("m"))
      .filter(name -> name.length() < 5)
      .collect(Collectors.toList());
}

复杂的谓词

@Test
public void whenFilterListWithComplexPredicate_thenSuccess(){
    List<String> result = names.stream()
      .filter(name -> name.startsWith("m") && name.length() < 5)
      .collect(Collectors.toList()); 
}

组合谓词

Predicate.and()
 
@Test
public void whenFilterListWithCombinedPredicatesUsingAnd_thenSuccess(){
    Predicate<String> predicate1 =  str -> str.startsWith("m");
    Predicate<String> predicate2 =  str -> str.length() < 5;
  
    List<String> result = names.stream()
      .filter(predicate1.and(predicate2))
      .collect(Collectors.toList()); 
}

Predicate.or()

@Test
public void whenFilterListWithCombinedPredicatesUsingOr_thenSuccess(){
    Predicate<String> predicate1 =  str -> str.startsWith("J");
    Predicate<String> predicate2 =  str -> str.length() < 4;
    
    List<String> result = names.stream()
      .filter(predicate1.or(predicate2))
      .collect(Collectors.toList()); 
}

Predicate.negate()

@Test
public void whenFilterListWithCombinedPredicatesUsingOrAndNegate_thenSuccess(){
    Predicate<String> predicate1 =  str -> str.startsWith("J");
    Predicate<String> predicate2 =  str -> str.length() < 4;
    
    List<String> result = names.stream()
      .filter(predicate1.or(predicate2.negate()))
      .collect(Collectors.toList()); 
}

通过Lambda表达式组合谓词

@Test
public void whenFilterListWithCombinedPredicatesInline_thenSuccess(){
    List<String> result = names.stream()
      .filter( ((Predicate<String>)name -> name.startsWith("m"))
               .and(name -> name.length()<5) )
      .collect(Collectors.toList());
}

组合谓词集合

@Test
public void whenFilterListWithCollectionOfPredicatesUsingAnd_thenSuccess(){
    List<Predicate<String>> allPredicates = new ArrayList<Predicate<String>>();
    allPredicates.add(str -> str.startsWith("m"));
    allPredicates.add(str -> str.contains("d"));        
    allPredicates.add(str -> str.length() > 4);
    
    List<String> result = names.stream()
      .filter(allPredicates.stream().reduce(x->true, Predicate::and))
      .collect(Collectors.toList()); 
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202208/16601004394206.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者