Guava(函数式编程)

Stella981
• 阅读 412

函数式编程:

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

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

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

/**
 * 日期转换
 */
public class DateFormatFunction implements Function<Date, String> {
    @Override
    public String apply(Date input) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
        return dateFormat.format(input);
    }
}

使用Functions类:

  • Functions.forMap()方法:

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

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

Map<String, State> states = new HashMap<String, State>();
Function<String, State> lookup = Functions.forMap(states);
System.out.println(lookup.apply(key));//key不存在会抛异常
 
//你也可以给不存在的key指定一个默认值
Function<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,查找某州的城市列表

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

等价于:

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

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

  • Predicate接口

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

如:

/**
 * 过滤人口小于500000的城市
 */
public class PopulationPredicate implements Predicate<City> {
    @Override
    public boolean apply(City input) {
        return input.getPopulation() <= 500000;
    }
}

使用Predicates类:

有两个过滤条件:

/**
 * 选择气候为TEMPERATE的城市
 */
public class TemperateClimatePredicate implements Predicate<City> {
    @Override
    public boolean apply(City input) {
        return input.getClimate().equals(Climate.TEMPERATE);
    }
}
 
/**
 * 选择雨量小于45.7的城市
 */
public class LowRainfallPredicate implements Predicate<City> {
    @Override
    public boolean apply(City input) {
        return input.getAverageRainfall() < 45.7;
    }
}

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

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

使用Supplier接口:

  • Supplier接口

    public interface Supplier {        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 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); //与之前不等

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
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
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
2星期前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Java修道之路,问鼎巅峰,我辈代码修仙法力齐天
<center<fontcolor00FF7Fsize5face"黑体"代码尽头谁为峰,一见秃头道成空。</font<center<fontcolor00FF00size5face"黑体"编程修真路破折,一步一劫渡飞升。</font众所周知,编程修真有八大境界:1.Javase练气筑基2.数据库结丹3.web前端元婴4.Jav
Stella981 Stella981
2年前
JS 对象数组Array 根据对象object key的值排序sort,很风骚哦
有个js对象数组varary\{id:1,name:"b"},{id:2,name:"b"}\需求是根据name或者id的值来排序,这里有个风骚的函数函数定义:function keysrt(key,desc) {  return function(a,b){    return desc ? ~~(ak
Stella981 Stella981
2年前
HIVE 时间操作函数
日期函数UNIX时间戳转日期函数: from\_unixtime语法:   from\_unixtime(bigint unixtime\, string format\)返回值: string说明: 转化UNIX时间戳(从19700101 00:00:00 UTC到指定时间的秒数)到当前时区的时间格式举例:hive   selec
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
6个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这