java基础7

来源:互联网 发布:thinkphp隐藏index.php 编辑:程序博客网 时间:2024/06/08 06:50

guava之只读函数式编程(过滤,转换,约束).集合

public class Basic {public static void main(String[] args) throws ParseException, FileNotFoundException, IOException {//只读控制List<String> list=new ArrayList<>();list.add("a");list.add("b");list.add("c");//对原有的list进行包装,相当于原有list的一个快照,视图List<String> readList=Collections.unmodifiableList(list);//readList.add("ee");//抛出异常,不能操作//list.add("d");//但是改变原有的列表之后,readList也一起改变,不够安全.//对比查看guava,相对更简单可靠.List<String> immutableList=ImmutableList.of("a", "b", "c", "d", "e", "f", "g");//immutableList.add("dd");//同样不能修改//函数式编程Predicate,Function//创建list,静态初始化List<String> list2=Lists.newArrayList("month","day","year","dad");//找出回文,过滤器//当该对象只使用一次可以考虑使用匿名内部类Collection<String> list3=Collections2.filter(list2, new Predicate<String>() {@Overridepublic boolean apply(String input) {// TODO 业务逻辑return new StringBuilder(input).reverse().toString().equals(input);//return true;}});for(String str:list3){System.out.println(str);System.out.println(new StringBuilder("dad").reverse().toString());}//类型转换Set<Long> sets=Sets.newHashSet();sets.add(111111111111111111L);sets.add(999999999999999999L);sets.add(77777777777777777L);Collection<String> csStrings=Collections2.transform(sets, new Function<Long, String>() {@Overridepublic String apply(Long input) {// TODO Auto-generated method stubreturn new SimpleDateFormat("yyyy-MM-dd").format(input);}});for(String tr:csStrings){System.out.println(tr);}//组合函数式编程//确保容器中的字符串长度不超过5,超过进行截取,后全部截断List<String> list4=Lists.newArrayList("chejinqian","good","happyness");Function<String, String> f1=new Function<String, String>() {@Overridepublic String apply(String input) {// TODO Auto-generated method stubreturn input.length()>5?input.substring(0, 5):input;}};Function<String, String> f2=new Function<String, String>() {@Overridepublic String apply(String input) {// TODO Auto-generated method stubreturn input.toUpperCase();}};//组合Function<String, String> f=Functions.compose(f1, f2);Collection<String> resultCollection=Collections2.transform(list4, f);for(String string:resultCollection){System.out.println(string);}}}
约束条件:

集合的操作:

public static void main(String[] args) throws ParseException, FileNotFoundException, IOException {//集合的操作:交,差,并Set<Integer> sets=Sets.newHashSet(1,2,3,4,5,6);Set<Integer> sets2=Sets.newHashSet(7,8,9,2,3,4,5,6);//交集SetView<Integer> setView=Sets.intersection(sets, sets2);for(Integer integer:setView){System.out.println(integer);}//差集SetView<Integer> setdiff=Sets.difference(sets, sets2);for(Integer integer:setdiff){System.out.println(integer);}//并集SetView<Integer> setCombine=Sets.union(sets, sets2);for(Integer integer:setCombine){System.out.println(integer);}}


统计每个单词的次数使用multiSet

//统计单词出现的次数//1.HashMap+分捡存储+面向对象思维//MultiSet:无序,可重复..count()String string="this is a good thing that where is not the food is";String[] strArray=string.split(" ");Multiset<String> multiset=HashMultiset.create();for(String string2:strArray){multiset.add(string2);}Set<String> letters=multiset.elementSet();for(String temp:letters){System.out.println(temp+"==="+multiset.count(temp));}
multiMap使用:

public static void main(String[] args) throws ParseException, FileNotFoundException, IOException {//分析查看教师    教授的每门课//MultiMap  key--value    key可以重复Map<String, String> map=new HashMap<String, String>();map.put("改革开放", "邓爷爷");map.put("三个代表", "江爷爷");map.put("科学发展观", "江爷爷");map.put("和谐社会", "胡爷爷");map.put("八荣", "胡爷爷");map.put("不知道", "席爷爷");map.put("大大的", "车爷爷");//multimapMultimap<String, String> mm=ArrayListMultimap.create();Iterator<Map.Entry<String, String>> it=map.entrySet().iterator();while(it.hasNext()){Map.Entry<String, String> tempEntry=it.next();String key=tempEntry.getKey();String value=tempEntry.getValue();mm.put(value, key);}//查看multimapSet<String> set=mm.keySet();for(String keys:set){System.out.println(keys+"---"+mm.get(keys));Collection<String> cs=mm.get(keys);}}

BiMap:键与值都不能重复的双向map

//HashMap:键唯 一,值可以重复//BiMap:键与值都不能重复.(如:根据邮箱找用户,根据用户找邮箱)BiMap<String, String> biMap=HashBiMap.create();biMap.put("a", "aaa@qq.com");biMap.put("b", "bbb@qq.com");//通过邮箱找用户String user=biMap.inverse().get("aaa@qq.com");System.out.println(biMap.inverse().inverse()==biMap);}


双键map::table...hashMap只有一个键

如:     A用户     数学      45分        rowKey+columnKey+value

方法::::::::::::

所有的行数据: cellSet()

所有的学生  rowKeySet()

所有的课程 columnKeySet()

所有的成绩 values()-->collection<>

学生对应的课程 rowMap().get(学生)   ||  row(学生)

课程对应的学生 columnMap().get(课程) || column(课程)

public class Basic {public static void main(String[] args) throws ParseException, FileNotFoundException, IOException {Table<String, String, Integer> table=HashBasedTable.create();table.put("a", "java", 20);table.put("b", "java", 20);table.put("c", "oracle", 11);table.put("a", "oracle", 200);//所有行数据Set<Cell<String, String, Integer>> set=table.cellSet();for(Cell<String, String, Integer> temp:set){System.out.println(temp.getRowKey()+"---"+temp.getColumnKey()+"----"+temp.getValue());}System.out.println("=======================================");System.out.print("学生\t");//所有的课程Set<String> cours=table.columnKeySet();for(String s:cours){System.out.print(s+"\t");}System.out.println();//所有的学生Set<String> stus=table.rowKeySet();for(String student:stus){System.out.print(student+"\t");Map<String, Integer> scores=table.row(student);for(String c:cours){System.out.print(scores.get(c)+"\t");}System.out.println();}System.out.println("=============转换,学生和课程转换==========================");Table<String, String, Integer> table2=Tables.transpose(table);//所有行数据Set<Cell<String, String, Integer>> set=table.cellSet();for(Cell<String, String, Integer> temp:set){System.out.println(temp.getRowKey()+"---"+temp.getColumnKey()+"----"+temp.getValue());}}}

Apache commons-collections:::提供一个类包来专门增加标准的java collections框架,处理数据灵活,与guava有相似之处.相互借鉴吧.哈哈.

下载地址:http://commons.apache.org/collections

MapIterator:很好用,以后不用map.keyset.iterator去处理map循环了.

----HashedMap

--BidiMap:用于 通过value查找key

----TreeBidiMap

--Bag:用于在集合中保存一个对象的多次拷贝

--HashBag

--Queue:-

--CollectionUtils:集合工具类

Predicate:对if条件的一种封装,该接口的唯一方法evaluate返回true或false. 

--Transformer

Closure:封装功能,实现解耦.

勤能补拙,努力就能成功.苦才胜过天才.何况苦才加天才呢.

public static void main(String[] args) throws ParseException, FileNotFoundException, IOException {//函数 编码,Predicate---->if ..else 的替代System.out.println("---------------------相等判断---------------------------");Predicate<String> pre=new EqualPredicate<String>("bjsxut");//第二种创建方式Predicate<String> pres=EqualPredicate.equalPredicate("che");boolean result=pre.evaluate("che");System.out.println(result);System.out.println("---------------------非空判断---------------------------");Predicate notnullPredicate=NotNullPredicate.INSTANCE;Predicate notnullPredicate2=NotNullPredicate.notNullPredicate();System.out.println(notnullPredicate.evaluate("che"));//非空为trueSystem.out.println("---------------------添加容器值判断---------------------------");List<Long> list=PredicatedList.predicatedList(new ArrayList<Long>(), notnullPredicate);list.add(222L);//list.add(null);//验证失败,抛异常 System.out.println("---------------------唯一性判断---------------------------");Predicate<Long> uniquePredicate=UniquePredicate.uniquePredicate();List<Long> list2=PredicatedList.predicatedList(new ArrayList<Long>(), uniquePredicate);list2.add(100L);list2.add(100L);//抛出异常System.out.println("---------------------自定义判断---------------------------");Predicate<String> selfPredicate=new Predicate<String>() {@Overridepublic boolean evaluate(String object) {// TODO Auto-generated method stubreturn object.length()>=5&&object.length()<=20;}};//PredicateUtils::::::   allPredicate(两个以上条件),  andPredicate(两个条件),  anyPredicate(任意一个条件满足即可)Predicate all=PredicateUtils.allPredicate(selfPredicate,notnullPredicate);//组合}

//transformer类型转化System.out.println("内置类型转化,长整型日期时间,转成指定格式的字符串");Transformer<Long, String> trans=new Transformer<Long, String>() {@Overridepublic String transform(Long input) {// TODO Auto-generated method stubreturn new SimpleDateFormat("yyyy-MM-dd").format(input);}};List<Long> list=new ArrayList<>();list.add(22222222L);list.add(111111111111L);Collection<String> cs=CollectionUtils.collect(list, trans);for(String str:cs){System.out.println(str);}//生成类的构造方法以及getter,setter方法的快捷键是alt+shift+sSystem.out.println("自定义类型的转换");Predicate<Employee> isLow=new Predicate<Employee>() {@Overridepublic boolean evaluate(Employee object) {// TODO Auto-generated method stubreturn object.getSalary()<10000;}};Predicate<Employee> isHigh=new Predicate<Employee>() {@Overridepublic boolean evaluate(Employee object) {// TODO Auto-generated method stubreturn object.getSalary()>=10000;}};Predicate[] presPredicates={isHigh,isLow};//自动转换开关.同时要写两个trans方法.复制上面的即可.然后便会自动关联起来,Transformer switchTransformer=new SwitchTransformer(presPredicates,trans2,null); 

函数式编程,closure,编程.封装特定的业务功能.

package basic;import java.io.FileNotFoundException;import java.io.IOException;import java.text.ParseException;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;public class Basic {@SuppressWarnings("unchecked")public static void main(String[] args) throws ParseException, FileNotFoundException, IOException {//函数式编程闭包------闭包------封装特定的业务功能basic();ifclosure();}//whileClosurepublic static void whileClosure() {//数据List<Employee> list=new ArrayList<>();list.add(new Employee("che",100000));list.add(new Employee("jin",100000));list.add(new Employee("qiang",300000));//业务Closure<Employee> cols=new Closure<Employee>() {public void execute(Employee input) {// TODO Auto-generated method stubinput.setSalary(input.getSalary()*1.2);}};Predicate<Employee> pre=new Predicate<Employee>() {public boolean evaluate(Employee object) {// TODO Auto-generated method stubreturn object.getSalary()<10000;}};//whileClosure<Employee> ce=WhileClosure.whileClosure(pre, cols,false);//true表示do..while结构,false表示while结构.一直循环,直到超过10000CollectionUtils.forAllDo(list, ce);//操作后的数据Iterator<Employee> emp=list.iterator();while (emp.hasNext()) {Employee employee = (Employee) emp.next();System.out.println(employee.getSalary());}}//ifClosurepublic static void ifclosure() {List<goods> list=new ArrayList<>();list.add(new goods("a",100,false));list.add(new goods("b",80,false));list.add(new goods("d",130,true));//满百减20Closure<goods> substract=new Closure<goods>() {public void execute(goods input) {input.setPrice(input.getPrice()-20);}};//打九折Closure<goods> substract2=new Closure<goods>() {public void execute(goods input) {input.setPrice(input.getPrice()*0.9);}};//判断Predicate<goods> pre=new Predicate<goods>() {public boolean evaluate(goods object) {return object.isDiscount();}};//二选一Closure<goods> cg=IfClosure.ifClosure(pre,substract2, substract);//折上减Closure<goods> cg2=ChainedClosure.chainedClosure(substract2,substract);//先打折,然后满百再减20CollectionUtils.forAllDo(list, cg);//操作后的数据Iterator<goods> emp=list.iterator();while (emp.hasNext()) {goods employee = (goods) emp.next();System.out.println(employee.getPrice());}}//基本操作public static void basic() {//数据List<Employee> list=new ArrayList<>();list.add(new Employee("che",100000));list.add(new Employee("jin",100000));list.add(new Employee("qiang",300000));//业务Closure<Employee> cols=new Closure<Employee>() {public void execute(Employee input) {// TODO Auto-generated method stubinput.setSalary(input.getSalary()*1.2);}};//工具类CollectionUtils.forAllDo(list, cols);//操作后的数据Iterator<Employee> emp=list.iterator();while (emp.hasNext()) {Employee employee = (Employee) emp.next();System.out.println(employee.getSalary());}}}

package basic;import java.io.FileNotFoundException;import java.io.IOException;import java.text.ParseException;import java.util.ArrayList;import java.util.Collection;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Queue;import java.util.Set;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.NotNullPredicate;import org.apache.commons.collections4.functors.WhileClosure;import org.apache.commons.collections4.queue.CircularFifoQueue;import org.apache.commons.collections4.queue.PredicatedQueue;import org.apache.commons.collections4.queue.UnmodifiableQueue;public class Basic {@SuppressWarnings("unchecked")public static void main(String[] args) throws ParseException, FileNotFoundException, IOException {//commons 之集合与队列Set<Integer> set=new HashSet<>();set.add(2);set.add(3);set.add(4);Set<Integer> set1=new HashSet<>();set1.add(2);set1.add(3);set1.add(4);//并集Collection<Integer> ci=CollectionUtils.union(set, set1);//交集ci=CollectionUtils.intersection(set, set1);ci=CollectionUtils.retainAll(set, set1);//差集ci=CollectionUtils.subtract(set, set1);//循环队列CircularFifoQueue<String> ccfq=new CircularFifoQueue<>(2);ccfq.add("A");ccfq.add("B");ccfq.add("C");//只读队列Queue<String> readOnlyQueue=UnmodifiableQueue.unmodifiableQueue(ccfq);readOnlyQueue.add("D");//抛出异常//断言队列Predicate notnull=NotNullPredicate.INSTANCE;Queue<String> que=PredicatedQueue.predicatedQueue(ccfq, notnull);que.add(null);//异常}}
//map迭代器System.out.println("------------------map迭代器----------------------");IterableMap<String, String> iMap=new HashedMap<>();iMap.put("a", "b");iMap.put("b", "e");iMap.put("c", "d");MapIterator<String,String> iterator=iMap.mapIterator();while(iterator.hasNext()){String key=iterator.next();String value=iterator.getValue();System.out.println(key+"---->"+value);}//去重迭代器List<String> list=new ArrayList<>();list.add("a");list.add("a");list.add("f");Iterator<String> it=new UniqueFilterIterator<>(list.iterator());while (it.hasNext()) {String string = (String) it.next();System.out.println(string);}//自定义过滤器list.add("dad");list.add("abc");Predicate<String> pre=new Predicate<String>() {public boolean evaluate(String object) {return new StringBuilder(object).reverse().toString().equals(object);}};Iterator<String> its=new FilterIterator(list.iterator(),pre);//循环迭代器Iterator<String> it2=new LoopingIterator(list);for(int i=0;i<5;i++){System.out.println(it2.next());}//数组迭代器int[] arr={1,2,3,4,5,6};Iterator<Integer> iiIterator=new ArrayListIterator<>(arr);

双向map::要求键与值都不能重复

BidiMap:1.DualTreeBidiMap有序      2.DualHashBidiMap:无序

//双向mapBidiMap<String, String> map=new DualHashBidiMap<>();map.put("c", "cc");map.put("d", "dd");//反转System.out.println(map.inverseBidiMap().get("cc"));MapIterator<String, String> mss=map.inverseBidiMap().mapIterator();while (mss.hasNext()) {String key = (String) mss.next();String value=mss.getValue();System.out.println(key+"---->"+value);}//有序,面向接口编程,改变实现类即可.//Bag包,允许重复,---->HashBag无序.TreeBag有序//可以用来统计单词的出现次数Bag<String> bag=new HashBag<>();bag.add("A");bag.add("a",9);//添加9个abag.add("b",2);//添加2个bbag.remove("a",2);Iterator<String> it=bag.iterator();while (it.hasNext()) {String string = (String) it.next();System.out.println(string);}int a=bag.getCount("a");// 统计}
抓住重点:

一张图:

二:三个知识点:

1.java.util.iterator+hasNext()+remove()

2.foreach:实现iterable接口,重写iterator方法

比较器:

实体类排序:java.lang.Comparable,+compareTo方法.或者提供排序比较集:comparator+compare

List+collections.sort()

treeset

treemap

3.泛型泛型类,泛型接口,泛型方法,泛型 擦除,通配符?

六个接口:Set,List,Map,Iterator,Comparable

九个常用类:

ArrayList:数组,查看多于修改.

LinkedList:链表

HashSet:重写hashcode+equals

TreeSet:元素可以排序或者提供排序的业务类

HashMap:键不可重复,重写hashcode+equals方法.

Properties:资源配置文件.

Stack

collections工具类


0 0
原创粉丝点击