当前位置: 代码迷 >> 综合 >> Apache Commons Collections基本操作(Predicate、Transformat、Closure等)
  详细解决方案

Apache Commons Collections基本操作(Predicate、Transformat、Closure等)

热度:19   发布时间:2024-01-09 19:14:01.0

一、Predicate断言

package Collections;import java.util.ArrayList;
import java.util.List;import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.PredicateUtils;
import org.apache.commons.collections4.functors.EqualPredicate;
import org.apache.commons.collections4.functors.NotNullPredicate;
import org.apache.commons.collections4.functors.UniquePredicate;
import org.apache.commons.collections4.list.PredicatedList;/*** 函数式编程之Predicate 断言* 封装条件或判别式if else替代* 1、 new EqualPredicate<类型>(值);* EqualPredicate.equalPredicate(值);* * 2、 NotNullPredicate.notNullPredicate* NotNullPredicate.INSTANCE* * PredicatedList.predicatedXxx(容器,判断)* * 3、 UniquePredicate.uniquePredicate()* * 4、 自定义 new Predicate类 + 重写evaluate方法* PredicateUtils.allPredicate 多于两个* andPredicate 两个* anyPredicate 其中一个* */
@SuppressWarnings("all")
public class Demo01 {
    public static void main(String[] args) {Test001();Test002();Test003();Test004();      }/*** 比较相等判断*/public static void Test001(){System.out.println("=====相等判断=======");Predicate<String> pre = new EqualPredicate<String>("liguodong");//Predicate<String> pre = EqualPredicate.equalPredicate("liguodong");//同上boolean flag = pre.evaluate("li");System.out.println(flag);       }/*** 非空判断*/public static void Test002(){System.out.println("=====非空判断=======");Predicate  notNull = NotNullPredicate.INSTANCE;//Predicate notNull = NotNullPredicate.notNullPredicate();//同上String str = "lgd";System.out.println(notNull.evaluate(str));//非空为true,否则为false。//添加容器值得判断List<Long> list = PredicatedList.predicatedList(new ArrayList<>(), notNull);list.add(1000L);//list.add(null);//null值为false, 验证失败,出现异常}public static void Test003(){System.out.println("=====唯一性判断=======");Predicate<Long> uniquePre = UniquePredicate.uniquePredicate();      List<Long> list = PredicatedList.predicatedList(new ArrayList<Long>(),uniquePre);list.add(100L);list.add(200L);//list.add(100L);//出现重复值,抛出异常}public static void Test004(){System.out.println("=====自定义判断=======");//自定义的判别式Predicate<String> selfPre = new Predicate<String>() {@Overridepublic boolean evaluate(String object) {return object.length()>=5&&object.length()<=20;}       };Predicate notNull = NotNullPredicate.notNullPredicate();//非空Predicate all = PredicateUtils.allPredicate(selfPre,notNull);       List<String> list = PredicatedList.predicatedList(new ArrayList<>(), all);list.add("liguodong");//list.add(null);//java.lang.NullPointerException//list.add("byby");//java.lang.IllegalArgumentException}
}

运行结果:

=====相等判断======= false
=====非空判断======= true
=====唯一性判断======= =====自定义判断=======

二、Transformat 类型转换

package Collections;
/*** 员工类*/
public class Employee {
    private String name;private double salary;//alt+/public Employee() {}//alt+shift+s +opublic Employee(String name, double salary) {super();this.name = name;this.salary = salary;}//alt+shift+s +r tab 回车 shift+tab 回车public String getName() {return name;}public void setName(String name) {this.name = name;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}@Overridepublic String toString() {return "(码农:"+this.name+",薪水:"+this.salary+")";}}
package Collections;public class Level {
    private String name;private String level;public Level() {}public Level(String name, String level) {super();this.name = name;this.level = level;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getLevel() {return level;}public void setLevel(String level) {this.level = level;}@Overridepublic String toString() {return "(码农:"+this.name+",水平:"+this.level+")";}
}
package Collections;import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.Transformer;
import org.apache.commons.collections4.functors.SwitchTransformer;/*** 解耦:将 业务处理与判断进行分离* * 函数式编程Transformat 类型转换* 1.Transformer+CollectionUtils.collect* * 2.SwitchTransformer* CollectionUtils.collect(容器,转换器)*/@SuppressWarnings("all")
public class Demo02 {
       public static void main(String[] args) {inner();define();}//内置类型的转化public static void inner(){System.out.println("========《内置类型转换 长整型时间日期,转成指定格式的字符串》========");//类型转换器Transformer<Long,String> trans = new Transformer<Long,String>(){@Overridepublic String transform(Long input) {return new SimpleDateFormat("yyyy年MM月dd日").format(input);}};//容器List<Long> list = new ArrayList<>();list.add(99999999L);list.add(30000L);//工具类:程序员出钱<---开发商--->农民工出力Collection<String> result = CollectionUtils.collect(list, trans);//遍历查看结果for(String time:result){System.out.println(time);}}//自定义类型转换public static void define(){System.out.println("==========《自定义类型转换》===========");Predicate<Employee> isLow = new Predicate<Employee>(){public boolean evaluate(Employee emp){return emp.getSalary()<=10000;}};              Predicate<Employee> isHigh = new Predicate<Employee>() {public boolean evaluate(Employee emp){return emp.getSalary()>=10000;}};  Predicate[] pres = {isLow,isHigh};//转换Transformer<Employee,Level> lowtrans = new Transformer<Employee,Level>(){   @Overridepublic Level transform(Employee input) {return new Level(input.getName(),"低薪");}};              //转换Transformer<Employee,Level> hightrans = new Transformer<Employee,Level>(){   @Overridepublic Level transform(Employee input) {return new Level(input.getName(),"高薪");}};      Transformer[] trans = {lowtrans,hightrans};//二者进行了关联Transformer switchTrans = new SwitchTransformer<>(pres, trans, null);List<Employee> list = new ArrayList<>();list.add(new Employee("凤姐",10000000));list.add(new Employee("犀利哥",1000));Collection<Level> levelList = CollectionUtils.collect(list, switchTrans);//遍历容器Iterator<Level> levelIt = levelList.iterator();while(levelIt.hasNext()){System.out.println(levelIt.next());}}
}

运行结果:

========《内置类型转换 长整型时间日期,转成指定格式的字符串》======== 1970年01月02日
1970年01月01日
==========《自定义类型转换》=========== (码农:凤姐,水平:高薪)
(码农:犀利哥,水平:低薪)

三、Closure 闭包封装业务功能

package Collections;
/*** 员工类*/
public class Employee {
    private String name;private double salary;//alt+/public Employee() {}//alt+shift+s +opublic Employee(String name, double salary) {super();this.name = name;this.salary = salary;}//alt+shift+s +r tab 回车 shift+tab 回车public String getName() {return name;}public void setName(String name) {this.name = name;}public double getSalary() {return salary;}public void setSalary(double salary) {this.salary = salary;}@Overridepublic String toString() {return "(码农:"+this.name+",薪水:"+this.salary+")";}}
package Collections;public class Goods {
    private String name;private double price;private boolean discount;//折扣public Goods() {}public Goods(String name, double price, boolean discount) {super();this.name = name;this.price = price;this.discount = discount;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public boolean isDiscount() {return discount;}public void setDiscount(boolean discount) {this.discount = discount;}@Overridepublic String toString() {return "(商品:"+this.name+",价格:"+this.price+",是否打折:"+(discount?"是":"否")+")";      }
}
package Collections;import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;import org.apache.commons.collections4.Closure;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.functors.ChainedClosure;
import org.apache.commons.collections4.functors.IfClosure;
import org.apache.commons.collections4.functors.WhileClosure;/*** 函数式编程Closure 闭包封装业务功能* 1. Closure* CollectionUtils.forAllDo(容器,功能类对象)* * 2. IfClosure * IfClosure.ifClosure(断言,功能1,功能2)* CollectionUtils.forAllDo(容器,功能类对象)* * 3. WhileClosure* WhileClosure.whileClosure(断言,功能,标识符)* CollectionUtils.forAllDo(容器,功能类对象)* * 4. ChainedClosure* ChainedClosure.chainedClosure(功能列表)* CollectionUtils.forAllDo(容器,功能类对象)* @author liguodong*/@SuppressWarnings("all")
public class Demo03 {
    public static void main(String[] args) {basic();System.out.println("==================");ifClousure();System.out.println("==================");whileClosure();System.out.println("==================");chainClousure();}//基本操作public static void basic(){//数据List<Employee> empList = new ArrayList<>();empList.add(new Employee("mark",20000));empList.add(new Employee("json",10000));empList.add(new Employee("Ivy",5000));//业务功能Closure<Employee> cols = new Closure<Employee>(){@Overridepublic void execute(Employee emp) {emp.setSalary(emp.getSalary()*1.2);}};//工具类CollectionUtils.forAllDo(empList, cols);        //操作后的数据Iterator<Employee> empIt = empList.iterator();while(empIt.hasNext()){System.out.println(empIt.next());}}/*** 二选一 如果打折商品,进行9折;否则满百减20。*/public static void ifClousure(){List<Goods> goodsList = new ArrayList<>();goodsList.add(new Goods("android视频",120,true));goodsList.add(new Goods("javaee视频",80,false));goodsList.add(new Goods("hadoop视频",150,false));//满百减20Closure<Goods> subtract = new Closure<Goods>() {@Overridepublic void execute(Goods input) {if(input.getPrice()>=100){input.setPrice(input.getPrice()-20);}           }};//打折Closure<Goods> discount = new Closure<Goods>() {@Overridepublic void execute(Goods input) {if(input.isDiscount()){input.setPrice(input.getPrice()*0.9);}           }};//判断Predicate<Goods> pre = new Predicate<Goods>() {@Overridepublic boolean evaluate(Goods goods) {return goods.isDiscount();}};//二选一Closure<Goods> ifClo = IfClosure.ifClosure(pre,discount,subtract);//关联CollectionUtils.forAllDo(goodsList,ifClo);  //查看操作后的数据for(Goods temp:goodsList){System.out.println(temp);}}/*** 确保所有的员工工资都大于10000,如果已经超过的不再上涨 。*/public static void whileClosure(){//数据List<Employee> empList = new ArrayList<>();empList.add(new Employee("周杰伦",20000));empList.add(new Employee("范冰冰",30000));empList.add(new Employee("黄晓明",5000));//业务功能 每次上涨0.2Closure<Employee> cols = new Closure<Employee>(){@Overridepublic void execute(Employee emp) {emp.setSalary(emp.getSalary()*1.2);}};//判断Predicate<Employee> empPre = new Predicate<Employee>() {@Overridepublic boolean evaluate(Employee emp) {return emp.getSalary()<10000;}};//false 表示while结构先判断后执行 //true 表示do..while先执行后判断Closure<Employee> whileCols = WhileClosure.whileClosure(empPre,cols,false); //工具类CollectionUtils.forAllDo(empList, whileCols);//操作后的数据Iterator<Employee> empIt = empList.iterator();while(empIt.hasNext()){System.out.println(empIt.next());}}   /***折上减 如果打折商品,先进行9折,如果还满百,再减20*/public static void chainClousure(){List<Goods> goodsList = new ArrayList<>();goodsList.add(new Goods("Android视频",120,true));goodsList.add(new Goods("javaee视频",100,false));goodsList.add(new Goods("Spack视频",80,false));//满百减20Closure<Goods> subtract = new Closure<Goods>() {@Overridepublic void execute(Goods input) {if(input.getPrice()>=100){input.setPrice(input.getPrice()-20);}}};//打折Closure<Goods> discount = new Closure<Goods>() {@Overridepublic void execute(Goods input) {if(input.isDiscount()){input.setPrice(input.getPrice()*0.9);}           }};//链式操作Closure<Goods> chinaClo = ChainedClosure.chainedClosure(discount,subtract);//关联CollectionUtils.forAllDo(goodsList,chinaClo);//查看操作后的数据for(Goods temp:goodsList){System.out.println(temp);}}
}

运行结果:

(码农:mark,薪水:24000.0)
(码农:json,薪水:12000.0)
(码农:Ivy,薪水:6000.0) ==================
(商品:android视频,价格:108.0,是否打折:是)
(商品:javaee视频,价格:80.0,是否打折:否)
(商品:hadoop视频,价格:130.0,是否打折:否) ==================
(码农:周杰伦,薪水:20000.0)
(码农:范冰冰,薪水:30000.0)
(码农:黄晓明,薪水:10368.0) ==================
(商品:Android视频,价格:88.0,是否打折:是)
(商品:javaee视频,价格:80.0,是否打折:否)
(商品:Spack视频,价格:80.0,是否打折:否)

四、集合操作

package Collections;import java.util.Collection;
import java.util.HashSet;
import java.util.Set;import org.apache.commons.collections4.CollectionUtils;/*** 集合操作* 1、并集 CollectionUtils.union* 2、交集 CollectionUtils.intersection* CollectionUtils.retainAll* 3、差集* CollectionUtils.subtract*/
public class Demo04 {public static void main(String[] args) {Set<Integer> set1 = new HashSet<>();set1.add(1);set1.add(2);set1.add(3);Set<Integer> set2 = new HashSet<>();set2.add(2);set2.add(3);set2.add(4);System.out.println("========并集==========");//并集Collection<Integer> col = CollectionUtils.union(set1, set2);for(Integer temp:col){System.out.print(temp+" ");}System.out.println("\n=========交集=========");//交集//col  = CollectionUtils.intersection(set1, set2);col  = CollectionUtils.retainAll(set1, set2);for(Integer temp:col){System.out.print(temp+" ");}       //差集System.out.println("\n=========差集=========");col  = CollectionUtils.subtract(set1, set2);for(Integer temp:col){System.out.print(temp+" ");}       }
}

运行结果:

========并集========== 1 2 3 4 
=========交集========= 2 3 
=========差集========= 1 

五、Queue队列

package Collections;import java.util.Queue;import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.functors.NotNullPredicate;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import org.apache.commons.collections4.queue.PredicatedQueue;
import org.apache.commons.collections4.queue.UnmodifiableQueue;/*** Queue队列* 1.循环队列* 2.只读队列:不可改变队列*/
@SuppressWarnings("all")
public class Demo05 {
    public static void main(String[] args) {circullar();readOnly();//predicate();}/*** 循环队列*/public static void circullar(){//长度是2,因此只能保留两个,循环着走。CircularFifoQueue<String> que = new CircularFifoQueue<>(2);que.add("a");que.add("b");que.add("c");que.add("d");//查看for(int i=0;i<que.size();i++){System.out.println(que.get(i));}}/*** 只读队列*/public static void readOnly(){CircularFifoQueue<String> que = new CircularFifoQueue<>(2);que.add("a");que.add("b");que.add("c");Queue<String> readOnlyOne = UnmodifiableQueue.unmodifiableQueue(que);//readOnlyOne.add("d");//java.lang.UnsupportedOperationException}/*** 断言队列*/public static void predicate(){//循环队列CircularFifoQueue<String> que = new CircularFifoQueue<>(2);que.add("a");que.add("b");que.add("c");Predicate notNull = NotNullPredicate.INSTANCE;//包装成对应的队列Queue<String> que2 = PredicatedQueue.predicatedQueue(que,notNull);//que2.add(null);//java.lang.IllegalArgumentException}
}

运行结果:

c
d

六、迭代器的扩展

package Collections;import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;import org.apache.commons.collections4.IterableMap;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.iterators.ArrayListIterator;
import org.apache.commons.collections4.iterators.FilterIterator;
import org.apache.commons.collections4.iterators.LoopingIterator;
import org.apache.commons.collections4.iterators.UniqueFilterIterator;
import org.apache.commons.collections4.map.HashedMap;/*** 迭代器的扩展* 1、MapIterator 以后不再使用map.keySet.iterator访问* IterableMap * HashedMap* 2、去重迭代器* UniqueFilterIterator* 3、自定义的过滤器* FilterIterator 自定义的过滤器+Predicate* 4、循环迭代器* LoopingIterator * 5、数组迭代器* ArrayListIterator* * @author liguodong*/
@SuppressWarnings("all")
public class Demo06 {
    public static void main(String[] args) {mapIt();uniqueIt();filterIt();loopIt();arrayIt();}/*** map迭代器*/public static void mapIt(){System.out.println("=======map迭代器=========");IterableMap<String,String> map = new HashedMap<>();     map.put("a", "baby");map.put("b", "ohyeah");map.put("c", "doog");//使用MapIteratorMapIterator<String,String> it = map.mapIterator();while(it.hasNext()){//移动游标 it.next()String key = it.next();//或者使用如下方法/*it.next();String key = it.getKey();*/String value = it.getValue();System.out.println(key+"-->"+value);            }}/*** 去重迭代器*/public static void uniqueIt(){System.out.println("=======去重迭代器=========");List<String> list = new ArrayList<>();list.add("a");list.add("b");list.add("a");//去掉重复的过滤器Iterator<String> it = new UniqueFilterIterator<>(list.iterator());while(it.hasNext()){System.out.println(it.next());}}/*** 自定义迭代器*/public static void filterIt(){System.out.println("======= 自定义迭代器=========");List<String> list = new ArrayList<>();list.add("abcba");list.add("dad");list.add("dsfa");//自定义的条件Predicate<String> pre = new Predicate<String>() {@Overridepublic boolean evaluate(String value) {//回文判断return new StringBuilder(value).reverse().toString().equals(value);}};//去重重复的过滤器Iterator<String> it = new FilterIterator(list.iterator(),pre);while(it.hasNext()){System.out.println(it.next());}}/*** 循环迭代器*/public static void loopIt(){System.out.println("======= 循环迭代器=========");List<String> list = new ArrayList<>();list.add("refer");list.add("dad");list.add("sdafds"); Iterator<String> it = new LoopingIterator<>(list);      for(int i=0;i<5;i++){System.out.println(it.next());}}/*** 数组迭代器*/public static void arrayIt(){System.out.println("=======数组迭代器=========");int[] str = {
   1,2,3,4,5};//Iterator<Integer> it = new ArrayListIterator<>(str);//也可以指定起始索引和结束索引Iterator<Integer> it = new ArrayListIterator<>(str,1,3);while(it.hasNext()){System.out.println(it.next());}       }   
}

运行结果:

=======map迭代器========= a-->baby
c-->doog
b-->ohyeah
=======去重迭代器========= a
b
======= 自定义迭代器========= abcba
dad
======= 循环迭代器========= refer
dad
sdafds
refer
dad
=======数组迭代器========= 2
3

七、双向Map

package Collections;import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
import org.apache.commons.collections4.bidimap.DualTreeBidiMap;/*** 双向Map要求键与值都不能重复* BidiMap接口 inverseBidiMap()反转方法* 1、DualTreeBidiMap:有序* 2、DualHashBidiMp:无序*/
public class Demo07 {
    public static void main(String[] args) {hashMap();treeMap();}   /*** 无序的双向Map*/ public static void hashMap(){System.out.println("=======无序的双向Map=========");BidiMap<String, String> map = new DualHashBidiMap<>();map.put("bj", "bj@test.com");map.put("ddssf", "ssdsfdsj@126.com");map.put("dsf", "bfdsfdsj@qq.com");//反转System.out.println(map.inverseBidiMap().get("bj@test.com"));//遍历查看MapIterator<String, String> it = map.inverseBidiMap().mapIterator();while(it.hasNext()){String key = it.next();String value = it.getValue();System.out.println(key+"-->"+value);}}/*** 有序的双向Map*/public static void treeMap(){System.out.println("=======有序的双向Map=========");BidiMap<String, String> map = new DualTreeBidiMap<>();map.put("bj", "bj@test.com");map.put("ddssf", "ssdsfdsj@126.com");map.put("dsf", "bfdsfdsj@qq.com");//遍历查看MapIterator<String, String> it = map.inverseBidiMap().mapIterator();while(it.hasNext()){String key = it.next();String value = it.getValue();System.out.println(key+"-->"+value);}}
}

运行结果:

=======无序的双向Map=========
bj
ssdsfdsj@126.com-->ddssf
bfdsfdsj@qq.com-->dsf
bj@test.com-->bj
=======有序的双向Map=========
bfdsfdsj@qq.com-->dsf
bj@test.com-->bj
ssdsfdsj@126.com-->ddssf

八、Bag包

package Collections;import java.util.Iterator;
import java.util.Set;import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.HashBag;
import org.apache.commons.collections4.bag.TreeBag;/*** Bag 包允许重复* 1.HashMap 无序* 2.TreeMap 有序* 统计单词的出现次数*/
public class Demo08 {public static void main(String[] args) {hashBag();treeBag();wordcount();//统计单词的出现次数 }//无序的包public static void hashBag(){System.out.println("=====无序的包========");Bag<String> bag = new HashBag<>();bag.add("a");bag.add("a",5);bag.remove("a",2);bag.add("b");bag.add("c");Iterator<String> it = bag.iterator();while(it.hasNext()){System.out.print(it.next()+" ");}System.out.println();}//有序的包public static void treeBag(){System.out.println("=====有序的包========");Bag<String> bag = new TreeBag<>();bag.add("a");bag.add("a",5);bag.remove("a",2);bag.add("b");bag.add("c");Iterator<String> it = bag.iterator();while(it.hasNext()){System.out.print(it.next()+" ");}System.out.println();}public static void wordcount(){String str = "this is a cat and that is a micewhere is the food";String[]  strArray  = str.split(" ");Bag<String> bag = new TreeBag<>();for(String temp:strArray){bag.add(temp);}System.out.println("=====统计次数========");Set<String> keys = bag.uniqueSet();for(String letter:keys){System.out.println(letter+"-->"+bag.getCount(letter));}}   
}

运行结果:

=====无序的包========
b c a a a a 
=====有序的包========
a a a a b c 
=====统计次数========
a-->2
and-->1
cat-->1
food-->1
is-->3
micewhere-->1
that-->1
the-->1
this-->1
  相关解决方案