Guava 精讲二

Predicate用于检查对象是否满足给定条件,主要用于通过 Iterables, Iterators, Collections2等filter()方法过滤集合元素,也经常用于Iterables.all()检测一组元素是否满足指定规则。Predicates类提供了很多有用的方法将多个对象组合在一起。

简单示例 - 检查country中是否有capital city定义

 @Test
    public void shouldUseCustomPredicate() throws Exception {
        // given
        Predicate<Country> capitalCityProvidedPredicate = new Predicate<Country>() {
            @Override
            public boolean apply(@Nullable Country country) {
                return !Strings.isNullOrEmpty(country.getCapitalCity());
            }
        };
        // when
        boolean allCountriesSpecifyCapitalCity = Iterables.all(
                Lists.newArrayList(Country.POLAND, Country.BELGIUM, Country.FINLAND_WITHOUT_CAPITAL_CITY),
                    capitalCityProvidedPredicate);
        // then
        assertFalse(allCountriesSpecifyCapitalCity);
    }

Predicate对象可以通过Predicates.and(), Predicates.or() and Predicates.not()方法进行组合

    @Test
    public void shouldComposeTwoPredicates() throws Exception {
        // given
        Predicate<Country> fromEuropePredicate = new Predicate<Country>() {
            @Override
            public boolean apply(@Nullable Country country) {
                return Continent.EUROPE.equals(country.getContinent());
            }
        };
        Predicate<Country> populationPredicate = new Predicate<Country>() {
            @Override
            public boolean apply(@Nullable Country country) {
                return country.getPopulation() < 20;
            }
        };
        Predicate<Country> composedPredicate = Predicates.and(fromEuropePredicate, populationPredicate);
        // when
        Iterable<Country> filteredCountries = Iterables.filter(Country.getSomeCountries(), composedPredicate);
        // then
        assertThat(filteredCountries).contains(Country.BELGIUM, Country.ICELAND);
    }

Predicates.containsPattern() - 用于正则表达式来产生条件

    @Test
    public void shouldCheckPattern() throws Exception {
        // given
        Predicate<CharSequence> twoDigitsPredicate = Predicates.containsPattern("\\d\\d");
        // then
        assertThat(twoDigitsPredicate.apply("Hello world 40")).isTrue();
    }

Predicates.in() - 一个对象是否存在于集合

    @Test
    public void shouldFindObjectInCollection() throws Exception {
        // given
        Predicate elevenInCollectionPredicate = Predicates.in(Arrays.asList(11L, 22L, 33L, 44L));
        // then
        assertThat(elevenInCollectionPredicate.apply(11L)).isTrue();
    }

你可能感兴趣的:(Guava 精讲二)