Google Guava学习笔记

Guava函数式编程(2)

2016-09-16  本文已影响98人  Viking_Den

使用Predicate接口

可以说Predicate接口和Function接口是具有相似的功能,Predicate接口也有两个方法:

public interface Predicate<T> {
   boolean apply(T input)
   boolean equals(Object object)
}

可以看出Predicate返回时boolean类型,对比Function接口主要是对输入的对象进行变换,而Predicate接口是对输入对象的过滤。
简单的示例,比如过滤出上一章节中所有城市中人口最小值的城市:

public class PopulationPredicate implements Predicate<City> {
     @Override
     public boolean apply(City input) {
           return input.getPopulation() <= 500000;
     }
}

使用Predicates类

直接上代码,定义两个关于城市特性的Predicate接口实现类:

public class TemperateClimatePredicate implements Predicate<City> {
   @Override
   public boolean apply(City input) {
         return input.getClimate().equals(Climate.TEMPERATE);
   }
}

public class LowRainfallPredicate implements Predicate<City> {
   @Override
   public boolean apply(City input) {
       return input.getAverageRainfall() < 45.7;
   }
}
Predicate smallAndDry =  Predicates.and(smallPopulationPredicate,lowRainFallPredicate);

如上的smallAndDry表示城市要同时人口少于500000,并且降雨量小于45.7。
Predicates.and方法参数有下面两个:

Predicates.and(Iterable<Predicate<T>> predicates);
Predicates.and(Predicate<T> ...predicates);
Predicate smallTemperate =
Predicates.or(smallPopulationPredicate,temperateClimatePredicate);

上面表示,在所有的城市中过滤,人口小于50000,或者降雨量小于45.7的城市。
同样的,Predicates.or有下面两个参数方法:

Predicates.or(Iterable<Predicate<T>> predicates);
Predicates.or(Predicate<T> ...predicates);

*使用Predicates.not
Predicates.not就是相反的,如果apply方法返回true,则为false;反之,则为true;

Predicate largeCityPredicate = Predicate.not(smallPopulationPredicate);
public class SouthwestOrMidwestRegionPredicate implements Predicate<State> {
       @Override
       public boolean apply(State input) {
             return input.getRegion().equals(Region.MIDWEST) ||
                       input.getRegion().equals(Region.SOUTHWEST);
       }
  }

下面就通过compose方法过滤出MIDWEST和SOUTHWEST的城市:

Predicate<String> predicate = Predicates.compose(southwestOrMidwestRegionPredicate,lookup);
上一篇下一篇

猜你喜欢

热点阅读