Guava(函数式编程)

函数式编程:

使用Function接口(jdk8中已经存在):

1/** 2 * 其功能就是将输入类型转换为输出类型 3 */ 4public interface Function<F, T> { 5  T apply(@Nullable F input); 6}

比如一个简单的日期转换:

1/** 2 * 日期转换 3 */ 4public class DateFormatFunction implements Function<Date, String> { 5    @Override 6    public String apply(Date input) { 7        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy"); 8        return dateFormat.format(input); 9    } 10}

使用Functions类:

  • Functions.forMap()方法:

    /**  * 州类  */ public class State {     private String name;     private String code;     private Set<City> mainCities = new HashSet<City>(); }

现在你想在一个Map<String, State>(key为州的编号)对象中查找某个key, 你可以:

1Map<String, State> states = new HashMap<String, State>(); 2Function<String, State> lookup = Functions.forMap(states); 3System.out.println(lookup.apply(key));//key不存在会抛异常 4  5//你也可以给不存在的key指定一个默认值 6Function<String, State> lookup = Functions.forMap(states, null);
  • Functions.compose()方法

    /城市类/ public class City {     private String name;     private String zipCode;     private int population;       @Override     public String toString() {         return name;     } }

    /**  * 将州的城市转换为字符串  */ public class StateToCityString implements Function<State, String> {     @Override     public String apply(State input) {         return Joiner.on(",").join(input.getMainCities());     } }

你可以通过组合Function,查找某州的城市列表

1Function<String, State> lookup = Functions.forMap(states); 2Function<State, String> stateFunction = new StateToCityString(); //州到城市的转换 3Function<String, String> stateCitiesFunction = Functions.compose(stateFunction, lookup); //组合Function 4System.out.println(stateCitiesFunction.apply(key));

等价于:

stateFunction.apply(lookup.apply(key));

使用Predicate接口(jdk8中已存在):

  • Predicate接口

    public interface Predicate<T> {      boolean apply(T input); //不同于Function.apply, 该apply用于过滤对象 }

如:

1/** 2 * 过滤人口小于500000的城市 3 */ 4public class PopulationPredicate implements Predicate<City> { 5    @Override 6    public boolean apply(City input) { 7        return input.getPopulation() <= 500000; 8    } 9}

使用Predicates类:

有两个过滤条件:

1/** 2 * 选择气候为TEMPERATE的城市 3 */ 4public class TemperateClimatePredicate implements Predicate<City> { 5    @Override 6    public boolean apply(City input) { 7        return input.getClimate().equals(Climate.TEMPERATE); 8    } 9} 10  11/** 12 * 选择雨量小于45.7的城市 13 */ 14public class LowRainfallPredicate implements Predicate<City> { 15    @Override 16    public boolean apply(City input) { 17        return input.getAverageRainfall() < 45.7; 18    } 19}

你可以运用下面的方法实现过滤组合等:

1Predicates.and(smallPopulationPredicate,lowRainFallPredicate);//且 2Predicates.or(smallPopulationPredicate,temperateClimatePredicate);//或 3Predicate.not(smallPopulationPredicate);//非 4Predicates.compose(smallPopulationPredicate,lookup);//组合转换再过滤

使用Supplier接口:

  • Supplier接口

    public interface Supplier<T> {        T get(); //用于创建对象 }

使用Suppliers类:

  • Suppliers.memorize()方法:

    SupplyCity sc = new SupplyCity(); System.out.println(Suppliers.memoize(sc).get()); System.out.println(Suppliers.memoize(sc).get());//返回同一对象, 单例

  • Suppliers.memorizeWithExpiration()方法:

    SupplyCity sc = new SupplyCity(); //超时再新建对象, 类似缓存 Supplier<City> supplier = Suppliers.memoizeWithExpiration(sc, 5, TimeUnit.SECONDS); City c = supplier.get(); System.out.println(c);  Thread.sleep(3000); c = supplier.get(); System.out.println(c); //与之前相等 Thread.sleep(2000); c = supplier.get(); System.out.println(c); //与之前不等

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )