Commons Collections函数编程

函数编程之Predicate(断言)

<br />

可以当作是封装条件或判别式 if...else的替代

常用类:

  1. 相等判断
  • new EqualPredicate<类型>(值);
  • EqualPredicate.equalPredicate(值);
  1. 非空判断
  • NotNullPredicate.INSTANCE;
  • NotNullPredicate.notNullPredicate();
  1. 添加容器值的判断是否符合要求可以用
    PredicateXxx.PredicateXxx(容器,判断);

  2. 唯一性判断

  • UniquePredicate.uniquePredicate();
    一般用于添加到容器的判断里面
  1. 自定义判断
  • new Predicate+evaluate的重写
  • 组合判断到一个里头
    • PredicateUtils.allPredicate 所有的
    • and (与) or (或)

示例程序

public static void test01() {
        // 相等判断
        Predicate<String> pre = EqualPredicate.equalPredicate("viking");
        boolean b = pre.evaluate(new String("viking"));
        System.out.println(b);

        // 非空判断
        Predicate notNull = NotNullPredicate.notNullPredicate();
        String string = "av";
        System.out.println(notNull.evaluate(string));

        // 唯一性判断
        Predicate<String> unique = UniquePredicate.uniquePredicate();
        List<String> uniqueList = PredicatedList.predicatedList(new ArrayList<>(), unique);
        uniqueList.add("a");
        uniqueList.add("b");
        // uniqueList.add("a"); 异常java.lang.IllegalArgumentException

        // 容器规范
        List<String> list = PredicatedList.predicatedList(new ArrayList<>(), notNull);
        list.add("viking");
        // list.add(null); 异常java.lang.IllegalArgumentException

        // 自定义判断
        Predicate<String> predicate = new Predicate<String>() {

            public boolean evaluate(String object) {
                return object.length() > 5 && object.length() < 15;
            }
        };

        Predicate all = PredicateUtils.allPredicate(predicate, notNull);
        List<String> list2 = PredicatedList.predicatedList(new ArrayList<>(), all);
        list2.add("viking");
        list2.add(null);//错误
    }

函数编程之Transformer(类型转换)

<br />

可以很方便的 转换整个容器
new Transformer + tansform方法重写
借助工具类CollectionUtils.collect(容器,规则);
可以达到目的

内置类型转换示例

public static void main(String[] args) {
        //时间对象转换为指定格式字符串
        Transformer<Date, String> trf = new Transformer<Date, String>() {

            public String transform(Date input) {
                //这里利用到了SimpleDateFormat类的format方法,此类中的parse方法是从指定格式字符串转换为时间对象的
                return new SimpleDateFormat("yyyy年MM月dd日").format(input);
            }
        };
        List<Date> list=new ArrayList<>();
        list.add(new Date(100000000L));
        list.add(new Date(999999999999L));
        //新建个容器存放转换过的内容
        Collection<String> list2=CollectionUtils.collect(list, trf);
        //遍历输出
        for(String temp:list2){
            System.out.println(temp);
        }
    }

自定义类型转换
将员工类转换为相应的等级的定义,根据工资
两个自定义类
员工类

public class Employee {
    private String name;
    private double salary;

    public Employee() {
    }

    public Employee(String name, double salary) {
        super();
        this.name = name;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "(码农:"+this.name+"码砖钱:"+this.salary+")";
    }

等级类

public class Level {
    String name;
    String level;
    
    public Level() {
    }

    public Level(String name, String level) {
        super();
        this.name = name;
        this.level = level;
    }

    @Override
    public String toString() {
        return "(码农:"+this.name+"等级:"+level+")";
    }

转换

public static void main(String[] args) {
        //高工资的判断
        Predicate<Employee> isHigh=new Predicate<Employee>() {

            public boolean evaluate(Employee object) {
                return object.getSalary()>=2000;
            }
        };
        //低工资的判断
        Predicate<Employee> isLow=new Predicate<Employee>() {

            public boolean evaluate(Employee object) {
                return object.getSalary()<2000;
            }
        };
        //存放进断言的数组里
        Predicate[] pre={isHigh,isLow};
        //转换为平民等级对象
        Transformer<Employee, Level> tranHigh=new Transformer<Employee, Level>() {

            public Level transform(Employee input) {
                return new Level(input.getName(), "搬砖平民");
            }
        };
        //转换为贵族等级对象
        Transformer<Employee, Level> tranLow=new Transformer<Employee, Level>() {

            public Level transform(Employee input) {
                return new Level(input.getName(), "搬砖贵族");
            }
        };
        //放进数组
        Transformer[] tran={tranHigh,tranLow};
        //这里的SwitchTransformer类是可以把断言数组和转换数组一一对应联系起来的,索引值相对应。返回一个转换
        Transformer swichTrans=new SwitchTransformer<>(pre, tran, null);
        
        List<Employee> employees=new ArrayList<>();
        employees.add(new Employee("viking", 2500));
        employees.add(new Employee("杨", 1800));
        employees.add(new Employee("杨V", 2000));
        //这里对他转换调用的还是之前的工具类里的静态方法,存进容器
        Collection<Level> col=CollectionUtils.collect(employees,swichTrans);
        //遍历输出
        for(Level temp:col){
            System.out.println(temp.toString());
        }

    }

函数编程之Closure(包装)

<br />

即封装业务功能,借助CollectionUtils.forAllDo(容器,Closure)方法可以很方便的对整个容器进行操作

  1. 基本的包装功能,这里示例程序包装了涨工资的操作
    public static void raise(List<Employee> list) {
        //涨工资操作包装
        Closure<Employee> clo = new Closure<Employee>() {

            public void execute(Employee input) {
                input.setSalary(input.getSalary() * 1.2);
            }
        };
        //借助工具类
        CollectionUtils.forAllDo(list, clo);
        
        for(Employee temp:list){
            System.out.println(temp);
        }
    }
  1. 功能二选一的操作,借助IfClosure,ifClosure(断言,trueClosure,falseClosur)可以通过判断选择进行相应的操作
    这里的示例程序
    public static void ifclosur(List<Employee> list){
        //低于一万的涨0.5
        Closure<Employee> Highclo = new Closure<Employee>() {

            public void execute(Employee input) {
                input.setSalary(input.getSalary() * 1.5);
            }
        };
        //高于一万的涨0.2
        Closure<Employee> Lowclo = new Closure<Employee>() {

            public void execute(Employee input) {
                input.setSalary(input.getSalary() * 1.2);
            }
        };
        //这里断言判断
        Predicate<Employee> pre=new Predicate<Employee>() {

            public boolean evaluate(Employee emp) {
                return emp.getSalary()>10000;
            }
        };
        //ifclosure返回一个closure
        Closure<Employee> closure=IfClosure.ifClosure(pre, Lowclo, Highclo);
        CollectionUtils.forAllDo(list, closure);
        
        for(Employee temp:list){
            System.out.println(temp);
        }
    }
  1. WhileClosure,相当于while或do..while
    借助WhileClosure.whileClosure(断言,功能,标识);这里如果是false则是while,如果是true则是do..while
public static void whileclosure(List<Employee> list){
        //功能1.2被涨工资
        Closure<Employee> clo = new Closure<Employee>() {

            public void execute(Employee input) {
                input.setSalary(input.getSalary() * 1.2);
            }
        };
        //断言
        Predicate<Employee> pre=new Predicate<Employee>() {

            public boolean evaluate(Employee emp) {
                return emp.getSalary()<10000;
            }
        };
        //满足断言的就一直while循环直到不满足
        Closure<Employee> closure=WhileClosure.whileClosure(pre, clo, false);
        CollectionUtils.forAllDo(list, closure);
        
        for(Employee temp:list){
            System.out.println(temp);
        }
    }
  1. ChainedClosure功能链
    ChainedClosure.chainedClosure(功能列表);
    这里个功能列表可以是个容器,也可以是挨个的Closure
    public static void chainedclosure(List<Employee> list){
        Closure<Employee> clo = new Closure<Employee>() {

            public void execute(Employee input) {
                input.setSalary(input.getSalary() * 1.2);
            }
        };
        
        Closure<Employee> changeclo = new Closure<Employee>() {

            public void execute(Employee input) {
                input.setName("帅气的"+input.getName());;
            }
        };
        //链接
        Closure<Employee> closure=ChainedClosure.chainedClosure(clo,changeclo);
        
        CollectionUtils.forAllDo(list, closure);
        
        for(Employee temp:list){
            System.out.println(temp);
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,653评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,321评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,833评论 0 324
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,472评论 1 266
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,306评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,274评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,658评论 3 385
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,335评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,638评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,697评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,454评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,311评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,699评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,986评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,254评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,647评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,847评论 2 335

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,502评论 18 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,510评论 18 399
  • 多态 任何域的访问操作都将有编译器解析,如果某个方法是静态的,它的行为就不具有多态性 java默认对象的销毁顺序与...
    yueyue_projects阅读 923评论 0 1
  • 上一篇博客中Java8函数式编程之三:函数式接口 - 简书留下的问题是关于Consumer接口的,本篇博客就来介绍...
    linkinparkzlz阅读 1,397评论 0 0
  • 最近总是很累很累。 不想结交新的朋友。 也不想联系以前的朋友。 但是,真的,很孤独,很害怕。 每一天,我都在担心灾...
    默静与光阅读 165评论 0 0