码迷,mamicode.com
首页 > 其他好文 > 详细

Guava基本用法

时间:2015-05-19 22:43:06      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

一、只读设置

package Guava;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.google.common.collect.ImmutableList;
/**
 * 只读设置
 */
public class Demo01 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        //对原有的List进行包装,相当于原有List的视图,快照,不够安全.
        List<String> readList = Collections.unmodifiableList(list);
        //java.lang.UnsupportedOperationException
        //readList.add("d");//报错
        list.add("d");//改变原有List   视图也一起改变  不报错
        System.out.println(readList);

        //Guava
        //对比查看  初始化List guava对只读设置安全可靠 并且相对简单
        List<String> immutableList = ImmutableList.of("a","b","c");
        //java.lang.UnsupportedOperationException
        //immutableList.add("d");//报错
        System.out.println(immutableList);
    }
}

运行结果:

[a, b, c, d]
[a, b, c]

二、函数式编程

package Guava;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 * 函数式编程:解耦
 * 1、Predicate 断言
 * 2、Function
 * 函数的组合式编程
 * Functions.compose(f1, f2);
 * 工具: Collections2.filter   过滤器
 *      Collections2.transform 转换
 */
public class Demo02 {
    public static void main(String[] args) {
        test1();//过滤器
        System.out.println("----------------");
        test2();
        System.out.println("----------------");
        test3();

    }

    //过滤器
    public static void test1()
    {
        //创建List 静态初始化
        List<String> list = Lists.newArrayList("SDF","SDAF","FASD","MOOM","ESDSE");
        //找出回文
        //匿名内部类对象:匿名内部类,同时创建类对象
        Collection<String> palindroomList = Collections2.filter(list, new Predicate<String>() {
            public boolean apply(String input)
            {
                //业务逻辑
                return new StringBuilder(input).reverse().toString().equals(input);
            }
        });

        for(String temp:palindroomList)
        {
            System.out.println(temp);
        }
    }

    //转换
    public static void test2()
    {
        //类型转换
        Set<Long> timeSet = Sets.newHashSet();
        timeSet.add(1000000L);
        timeSet.add(999999999999L);
        timeSet.add(20000000L);

        Collection<String> timeStrCol = Collections2.transform(timeSet, new Function<Long, String>() {
            @Override
            public String apply(Long input) {
                return new SimpleDateFormat("yyyy-MM-dd").format(input);
            }
        });

        for(String temp:timeStrCol)
        {
            System.out.println(temp);
        }
    }

    //组合式函数编程
    public static void test3(){
        //确保容器中的字符串长度不超过5,超过进行截取,后全部大写
        List<String> list = Lists.newArrayList("lovebaby","good","happiness");

        //确保容器中的字符串长度不超过5,超过进行截取
        Function<String, String> f1 = new Function<String, String>() {
            @Override
            public String apply(String input) {
                return input.length()>5?input.substring(0,5):input;
            }
        };

        //全部大写
        Function<String, String> f2 = new Function<String, String>() {
            @Override
            public String apply(String input) {
                return input.toUpperCase();
            }
        };

        //组合使用
        //String = f2(f1(String))
        Function<String, String> f = Functions.compose(f1, f2);

        Collection<String> resultCol = Collections2.transform(list,f);

        for(String temp:resultCol)
        {
            System.out.println(temp);
        }
    }       
}

运行结果:

MOOM
ESDSE
----------------
1970-01-01
1970-01-01
2001-09-09
----------------
LOVEB
GOOD
HAPPI

三、约束条件

package Guava;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Collection;
import java.util.Set;

import com.google.common.collect.ForwardingSet;
import com.google.common.collect.Lists;

/**
 * 解决guava-18.0.jar不能使用
 * com.google.common.collect.Constraints、
 * com.google.common.collect.Constraint 的问题。
 * @author liguodong
 * @param <E>
 */
interface Constraint<E>{
    //public String checkElement(String element);
    E checkElement(E element);
}

class Constraints<E>{
    public static <E> Set<E> constrainedSet(
              Set<E> set, Constraint<? super E> constraint) {
            return new ConstrainedSet<E>(set, constraint);
          }
     private static <E> Collection<E> checkElements(
              Collection<E> elements, Constraint<? super E> constraint) {
            Collection<E> copy = Lists.newArrayList(elements);
            for (E element : copy) {
              constraint.checkElement(element);
            }
            return copy;
          }
     /** @see Constraints#constrainedSet */
     static class ConstrainedSet<E> extends ForwardingSet<E> {
       private final Set<E> delegate;
       private final Constraint<? super E> constraint;

       public ConstrainedSet(Set<E> delegate, Constraint<? super E> constraint) {
         this.delegate = checkNotNull(delegate);
         this.constraint = checkNotNull(constraint);
       }
       @Override protected Set<E> delegate() {
         return delegate;
       }
       @Override public boolean add(E element) {
         constraint.checkElement(element);
         return delegate.add(element);
       }
       @Override public boolean addAll(Collection<? extends E> elements) {
         return delegate.addAll(checkElements(elements, constraint));
       }
     }
}
package Guava;

import java.util.Set;

import com.google.common.base.Preconditions;
//import com.google.common.collect.Constraint;
//import com.google.common.collect.Constraints;
import com.google.common.collect.Sets;


/**
 * 加入约束条件:非空,长度验证
 * Constraint
 * Precondiotions
 * Constrains
 */
public class Demo03 {
    public static void main(String[] args) {
        Set<String> sets = Sets.newHashSet();
        //创建约束
        Constraint<String> constraint = new Constraint<String>() {
            @Override
            public String checkElement(String element) {
                //非空验证
                Preconditions.checkNotNull(element);
                //长度验证5-20
                Preconditions.checkArgument(element.length()>=5&&element.length()<=20);     
                return element;
            }               
        };      
        Set<String> cs = Constraints.constrainedSet(sets, constraint);
        //cs.add(null);// java.lang.NullPointerException
        //cs.add("doog");//java.lang.IllegalArgumentException
        cs.add("liguodong");
        for(String temp:cs)
        {
            System.out.println(temp);
        }
    }
}

运行结果:

liguodong

四、集合的操作

package Guava;

import java.util.Set;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;

/**
 * 集合的操作:交集,差集,并集
 * Sets.intersection()
 * Sets.difference()
 * Sets.union()
 */

public class Demo04 {
    public static void main(String[] args) {
        Set<Integer> sets = Sets.newHashSet(1,2,3,4,5,6);
        Set<Integer> sets2 = Sets.newHashSet(3,4,5,6,7,8,9);

        //交集
        System.out.println("交集为:");
        SetView<Integer> intersection = Sets.intersection(sets, sets2);
        for(Integer temp:intersection)
        {
            System.out.print(temp+" ");
        }
        System.out.println();
        //差集
        System.out.println("差集为:");
        SetView<Integer> diff = Sets.difference(sets, sets2);
        for(Integer temp:diff)
        {
            System.out.print(temp+" ");
        }
        System.out.println();
        //并集
        System.out.println("并集为:");
        SetView<Integer> union = Sets.union(sets, sets2);
        for(Integer temp:union)
        {
            System.out.print(temp+" ");
        }
        System.out.println();
    }
}

运行结果:

交集为:
3 4 5 6 
差集为:
1 2 
并集为:
1 2 3 4 5 6 7 8 9 

五、MultiSet

package Guava;

import java.util.Set;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;

/**
 * 统计单词出现的次数
 * 1.HashMap 分拣存储+面向对象思维-->判断
 * 2.MultiSet:无序+可重复   count()方法获取单词的次数  增强了可读性+操作简单
 */

public class Demo05 {
    public static void main(String[] args) {
        String str = "this is a cat that is a mice where is the food";
        //分割字符串
        String[] strArray = str.split(" ");
        //存储到Multiset中
        Multiset<String> set = HashMultiset.create();
        for(String temp :strArray)
        {
            set.add(temp);
        }
        //获取所有的单词Set
        Set<String> letters = set.elementSet();
        for(String temp:letters)
        {
            System.out.println(temp+"-->"+set.count(temp));
        }
    }
}

运行结果:

mice-->1
that-->1
cat-->1
is-->3
food-->1
a-->2
the-->1
where-->1
this-->1

六、Multimap

package Guava;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

/**
 * 分析查看 教师 教授 的每门课程
 * Multimap:key-value  key可以重复
 */
public class Demo06 {
    public static void main(String[] args) {
        Map<String,String> cours = new HashMap<>();
        //加入测试数据 
        cours.put("改革开放","邓小平");
        cours.put("三个代表","江泽民");
        cours.put("和谐社会","胡锦涛");
        cours.put("八荣八耻","胡锦涛");
        cours.put("互联网+","李克强");
        //Multimap
        Multimap<String, String> teachers = ArrayListMultimap.create();
        //迭代器
        Iterator<Map.Entry<String, String>> it = cours.entrySet().iterator();
        while(it.hasNext())
        {
            Map.Entry<String, String> entry = it.next();
            String key = entry.getKey();//课程
            String value = entry.getValue();//教师
            //教师-->课程
            teachers.put(value,key);
        }       
        //查看Multimap
        Set<String> keyset = teachers.keySet();
        for(String key:keyset)
        {
            Collection<String> col = teachers.get(key);
            System.out.println(key+"-->"+col); 
        }
    }
}

运行结果:

邓小平-->[改革开放]
江泽民-->[三个代表]
胡锦涛-->[八荣八耻, 和谐社会]
李克强-->[互联网+]

七、BiMap

package Guava;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

/**
 * HashMap 键唯一,值可以重复
 * BiMap:双向Map(Bidirectional Map) 键与值都不能重复(unique -valued map)
 */
public class Demo07 {
    public static void main(String[] args) {
        BiMap<String, String> biMap = HashBiMap.create();
        biMap.put("liguodong", "liguodong@sina.com");
        biMap.put("good","good@qq.com");
        //通过邮箱找用户
        String user = biMap.inverse().get("good@qq.com");
        System.out.println(user);
        System.out.println( biMap.inverse().inverse()==biMap );
    }
}

运行结果:

good
true

八、双键的Map

package Guava;

import java.util.Map;
import java.util.Set;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.common.collect.Table.Cell;
import com.google.common.collect.Tables;

/**
 * 双键的Map--> Table-->rowKey+columnKey+value
 * 1.方法
 *   所有的行数据:cellSet()
 *   所有的学生:rowKeySet()
 *   所有的课程:columnKeySet()
 *   所有的成绩:values()
 *   学生对应的课程:rowMap()+get(学生)
 *               row(学生)
 *   
 *   课程对应的学生:columnMap()+get(课程)
 *               column(课程) 
 */
public class Demo08 {
    public static void main(String[] args) {
        Table<String, String, Integer> tables = HashBasedTable.create();
        //测试数据
        tables.put("a", "javase", 80);
        tables.put("b", "javase", 90);
        tables.put("a", "oracle", 100);
        tables.put("c", "javase", 95);

        //所有的行数据
        Set<Cell<String, String, Integer>> cells = tables.cellSet();
        for(Cell<String, String, Integer> temp:cells)
        {
            System.out.println(temp.getRowKey()+"-->"+temp.getColumnKey()+"-->"+temp.getValue());
        }


        System.out.println("=======学生查看成绩============");
        System.out.print("学生\t");
        //所有的课程
        Set<String> cours = tables.columnKeySet();
        for(String t:cours)
        {
            System.out.print(t+"\t");
        }
        System.out.println();

        //所有的学生
        Set<String> stus = tables.rowKeySet();

        for(String stu:stus)
        {
            System.out.print(stu+"\t");//输出学生

            //以下是输出学生的每一门课程
            Map<String,Integer> scores = tables.row(stu);//<课程,分数>

            for(String c:cours)//课程
            {
                System.out.print(scores.get(c)+"\t");
            }
            System.out.println();
        }


        System.out.println("=======课程查看成绩============");
        System.out.print("课程\t");
        //所有的学生
        Set<String> stus1 = tables.rowKeySet();

        for(String t:stus1)
        {
            System.out.print(t+"\t");
        }
        System.out.println();

        //所有的课程
        Set<String> cours1 = tables.columnKeySet();

        for(String c:cours1)
        {
            System.out.print(c+"\t");//课程
            Map<String,Integer> scores = tables.column(c);//<学生,分数>
            for(String s:stus1)
            {
                System.out.print(scores.get(s)+"\t");
            }
            System.out.println();
        }

        System.out.println("=======转换===========");
        Table<String, String, Integer> tables2 = Tables.transpose(tables);

        //所有的行数据
        Set<Cell<String, String, Integer>> cells2 = tables2.cellSet();
        for(Cell<String, String, Integer> temp:cells2)
        {
            System.out.println(temp.getRowKey()+"-->"+temp.getColumnKey()+"-->"+temp.getValue());
        }
    }
}

运行结果:

b-->javase-->90
c-->javase-->95
a-->oracle-->100
a-->javase-->80
=======学生查看成绩============
学生  javase  oracle  
b   90  null    
c   95  null    
a   80  100 
=======课程查看成绩============
课程  b   c   a   
javase  90  95  80  
oracle  null    null    100 
=======转换===========
javase-->b-->90
javase-->c-->95
oracle-->a-->100
javase-->a-->80

Guava基本用法

标签:

原文地址:http://blog.csdn.net/scgaliguodong123_/article/details/45849921

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!