函数式编程:
转载自:http://my.oschina.net/indestiny/blog/215041
使用Function接口(jdk8中已经存在):
4 |
public interface Function<F,
T> { |
5 |
T
apply( @Nullable F
input); |
比如一个简单的日期转换:
04 |
public class DateFormatFunction implements Function<Date,
String> { |
06 |
public String
apply(Date input) { |
07 |
SimpleDateFormat
dateFormat = new SimpleDateFormat( "dd/mm/yyyy" ); |
08 |
return dateFormat.format(input); |
使用Functions类:
7 |
private Set<City>
mainCities = new HashSet<City>(); |
现在你想在一个Map<String, State>(key为州的编号)对象中查找某个key, 你可以:
1 |
Map<String,
State> states = new HashMap<String,
State>(); |
2 |
Function<String,
State> lookup = Functions.forMap(states); |
3 |
System.out.println(lookup.apply(key)); |
6 |
Function<String,
State> lookup = Functions.forMap(states, null ); |
04 |
private String
zipCode; |
05 |
private int population; |
08 |
public String
toString() { |
4 |
public class StateToCityString implements Function<State,
String> { |
6 |
public String
apply(State input) { |
7 |
return Joiner.on( "," ).join(input.getMainCities()); |
你可以通过组合Function,查找某州的城市列表
1 |
Function<String,
State> lookup = Functions.forMap(states); |
2 |
Function<State,
String> stateFunction = new StateToCityString(); |
3 |
Function<String,
String> stateCitiesFunction = Functions.compose(stateFunction, lookup); |
4 |
System.out.println(stateCitiesFunction.apply(key)); |
等价于:
1 |
stateFunction.apply(lookup.apply(key)); |
使用Predicate接口(jdk8中已存在):
1 |
public interface Predicate<T>
{ |
2 |
boolean apply(T
input); |
如:
4 |
public class PopulationPredicate implements Predicate<City>
{ |
6 |
public boolean apply(City
input) { |
7 |
return input.getPopulation()
<= 500000 ; |
使用Predicates类:
有两个过滤条件:
04 |
public class TemperateClimatePredicate implements Predicate<City>
{ |
06 |
public boolean apply(City
input) { |
07 |
return input.getClimate().equals(Climate.TEMPERATE); |
14 |
public class LowRainfallPredicate implements Predicate<City>
{ |
16 |
public boolean apply(City
input) { |
17 |
return input.getAverageRainfall()
< 45.7 ; |
你可以运用下面的方法实现过滤组合等:
1 |
Predicates.and(smallPopulationPredicate,lowRainFallPredicate); |
2 |
Predicates.or(smallPopulationPredicate,temperateClimatePredicate); |
3 |
Predicate.not(smallPopulationPredicate); |
4 |
Predicates.compose(smallPopulationPredicate,lookup); |
使用Supplier接口:
1 |
public interface Supplier<T>
{ |
使用Suppliers类:
1 |
SupplyCity
sc = new SupplyCity(); |
2 |
System.out.println(Suppliers.memoize(sc).get()); |
3 |
System.out.println(Suppliers.memoize(sc).get()); |
- Suppliers.memorizeWithExpiration()方法:
01 |
SupplyCity
sc = new SupplyCity(); |
02 |
Supplier<City>
supplier = Suppliers.memoizeWithExpiration(sc, 5 ,
TimeUnit.SECONDS); |
03 |
City
c = supplier.get(); |
04 |
System.out.println(c); |
07 |
System.out.println(c); |
10 |
System.out.println(c); |
Guava函数式编程基础,后面集合处理中,将体现得更强大。
不吝指正。