函数式编程
主要是2个方面:
- Predicate
- Function
Predicate主要是用来判断条件是不是成立,而Function是用来执行实际的操作的。
Predicate和Predicates
Predicate是接口的定义,而Predicates是内在提供的一些常用实现。
常用的方法
- instanceOf(Class)
- assignableFrom(Class)
- contains(Pattern)
- in(Collection)
- isNull()
- alwaysFalse(), alwaysTrue()
- equalTo(Object)
- compose(Predicate, Function)
- and(Predicate...), or(Predicate...), not(Predicate)
简单使用
Predicate<CountryEnum> fromAsiaPredicate = new Predicate<CountryEnum>() {
@Override
public boolean apply(@Nullable CountryEnum country) {
return country.getContinent().equals("ASIA");
}
};
Predicate<CountryEnum> historyPredicate = new Predicate<CountryEnum>() {
@Override
public boolean apply(@Nullable CountryEnum country) {
return country.getAge() > 1000;
}
};
Predicate<CountryEnum> composedPredicate = Predicates.and(fromAsiaPredicate, historyPredicate);
Iterable<CountryEnum> filteredCountries = Iterables.filter(CountryEnum.findCountries(), composedPredicate);
Iterator iterator = filteredCountries.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Function和Functions
Function是接口的定义,而Functions是内在提供的一些常用实现。
常用的方法
简单实用
Function<Country, String> upperCaseFunction = new Function<Country, String>() {
@Override
public String apply(@Nullable CountryEnum country) {
if (country == null) {
return "";
}
return country.getCapital().toUpperCase();
}
};
//倒排名称
Function<String, String> reverseFunction = new Function<String, String>() {
@Override
public String apply(String s) {
if (s == null) {
return null;
}
return new StringBuilder(s).reverse().toString();
}
};
//混合方法
Function<Country, String> composeFunction = Functions.compose(reverseFunction, upperCaseFunction);
List<String> capitals = Lists.transform(countryList.findCountries(), composeFunction);