Java 8谓词(Predicate)链简介说明
下文笔者讲述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()); }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。