关于 google的guava公共库的测试demo

最近在学习,guava公共库的一些基本功能,确实的是可以提高开发效率,并且有些地方确实很好用。

代码可以直接打开需要测试的地方进行运行。

不包含,net,事件总线,并发编程,反射和缓存。

手册地址:http://tool.oschina.net/apidocs/apidoc?api=guava

中文学习:http://ifeve.com/google-guava-using-and-avoiding-null

总的来说,印象深刻的就是,multiset和multimap这2个概念,很有用。当然还是有很多精彩的细节地方,学会了事半功倍。学习测试一下api吧

package com.iqoo.common;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.junit.Test;

import com.google.common.base.Charsets;
import com.google.common.base.Objects;
import com.google.common.io.Files;

/**
 * Created by hank on 2016/6/3.
 */
public class demo {

    @Test
    public void test() throws IOException, SQLException, InvalidFormatException {
        // optional 模拟,对象引用为null,返回默认值
        // Optional possible = Optional.fromNullable(null);
        // System.out.println(possible.or(2));

        // 提前条件预判,抛出异常
        // Preconditions.checkNotNull(null,"this is error");

        // objects判断null相等
        // System.out.println(Objects.equal(null, null));

        // hashcode通过传入不同的字段,自动计算
        // System.out.println(Objects.hashCode("han","kun"));
        // System.out.println(Objects.hashCode("han","kun",1));
        // System.out.println(Objects.hashCode("han","kun",1));

        // toStringHelper编写调试
//        System.out.println(Objects.toStringHelper(this).add("name", "hank").toString());

        // compareTo这种对比,多个字段的时候
        // System.out.println(ComparisonChain.start().compare(1, 3).result());
        // System.out.println(ComparisonChain.start().compare('a', 'b').result());

        // ordering比较器
        // List<Integer> list = Lists.newArrayList();
        // list.add(1);
        // list.add(2);
        // list.add(3);
        // list.add(11);
        // list.add(21);
        // Ordering<Integer> naturalOrdering = Ordering.natural();
        // Ordering<Object> usingToStringOrdering = Ordering.usingToString();
        // Ordering<Object> arbitraryOrdering = Ordering.arbitrary();
        // System.out.println("自然顺序(数字大小):"+ naturalOrdering.sortedCopy(list));
        // System.out.println("字符串顺序:"+ usingToStringOrdering.sortedCopy(list));
        // System.out.println("随机顺序:"+ arbitraryOrdering.sortedCopy(list));

        // 捕获异常后,继续抛出异常
        // try {
        // int a = 1;
        // throw new IOException();
        // throw new SQLException();
        // }
        // catch (Throwable t) {
        // 只有io异常抛出
        // Throwables.propagateIfInstanceOf(t, IOException.class);
        // 只有sql异常抛出
        // Throwables.propagateIfInstanceOf(t, SQLException.class);
        // 只有Error或RuntimeException异常抛出
        // Throwables.propagateIfPossible(t);
        // Error或RuntimeException,直接抛出
        // throw Throwables.propagate(t);
        // }

        // 不可变集合
        // final ImmutableSet<String> colors = ImmutableSet.of("red","blue","green");
        // ImmutableList<String> colorsList = colors.asList();
        // System.out.println(colors.size());
        // 重复的set
        // Multiset m = HashMultiset.create();
        // m.add("han");
        // m.add("han");
        // m.add("han");
        // m.add("kun");
        // System.out.println(m.count("han"));

        // Multimap<String, String> myMultimap = ArrayListMultimap.create();
        //
        // 添加键值对
        // myMultimap.put("Fruits", "Bannana");
        // 给Fruits元素添加另一个元素
        // myMultimap.put("Fruits", "Apple");
        // myMultimap.put("Fruits", "Pear");
        // myMultimap.put("Vegetables", "Carrot");
        // myMultimap.put("Fruits", "Bannana");
        // System.out.println(myMultimap.get("Fruits"));

        // Multimap<String,String> map = HashMultimap.create();
        // map.put("name","han");
        // map.put("name","kkkk");
        // map.put("yourname","xxx");
        // map.put("yourname","yyy");
        // map.put("yourname","www");
        // System.out.println(map.get("name"));
        // System.out.println(map.size());
        // System.out.println(map.keySet());
        // 区别,一个为空集合,一个为null
        // System.out.println(map.get("hello"));
        // System.out.println(map.asMap().get("hello"));

        // BiMap<String, Integer> userId = HashBiMap.create();
        // userId.put("hank",123);
        // 反向映射
        // System.out.println(userId.forcePut("hank",345));
        // System.out.println(userId.inverse().get(123));
        // System.out.println(userId.inverse().get(345));

        // 二维坐标确定一个值
        // Table<Integer, Integer, String> pos = HashBasedTable.create();
        // pos.put(1,1,"han");
        // pos.put(1,2,"hello");
        // pos.put(2,1,"world");
        // pos.put(2,2,"kun");
        // System.out.println(pos.row(1));
        // System.out.println(pos.column(1));
        // System.out.println(pos.cellSet().size());

        // RangeSet<Integer> range = TreeRangeSet.create();
        // range.add(Range.open(1,2));
        // range.add(Range.open(2,3));
        // range.add(Range.open(4,5));
        // range.add(Range.open(6,10));
        // 包含所有区间的最小区间
        // System.out.println(range.span());
        // System.out.println(range);
        // 区间补集
        // System.out.println(range.complement());
        // System.out.println(range.asRanges());
        // System.out.println(range.contains(2));
        // 返回包含的区间
        // System.out.println(range.rangeContaining(2));
        // 是否包含区间
        // System.out.println(range.encloses(Range.open(3,4)));
        // System.out.println(range.encloses(Range.open(4,5)));
        // System.out.println(range.encloses(Range.open(5,6)));
        // System.out.println(range.encloses(Range.open(5,7)));
        // 是否和子区间相交
        // System.out.println(range.subRangeSet(Range.open(3,4)).isEmpty());
        // System.out.println(range.subRangeSet(Range.open(4,5)).isEmpty());
        // System.out.println(range.subRangeSet(Range.open(5,6)).isEmpty());
        // System.out.println(range.subRangeSet(Range.open(5,7)).isEmpty());

        // RangeMap<Integer,String> map = TreeRangeMap.create();
        // map.put(Range.open(1,2),"han");
        // map.put(Range.open(2,3),"kun");
        // System.out.println(map);
        // 注意区别,覆盖了上面的区间
        // map.put(Range.open(1,3),"hello");
        // System.out.println(map);

        // List<String> theseElements = Lists.newArrayList("alpha", "beta", "gamma");
        // System.out.println(theseElements);

        // Iterable<Integer> concatenated = Iterables.concat(
        // Ints.asList(1, 2, 3),
        // Ints.asList(4, 5, 6)); // concatenated包括元素 1, 2, 3, 4, 5, 6
        // System.out.println(concatenated);
        // List countUp = Ints.asList(1, 2, 3, 4, 5);
        // System.out.println(countUp);
        // List countDown = Lists.reverse(countUp); // {5, 4, 3, 2, 1}
        // System.out.println(countDown);
        // List<List> parts = Lists.partition(countUp, 2);//{{1,2}, {3,4}, {5}}
        // System.out.println(parts);

        // List strs = Lists.newArrayList("han","hello","name");
        // 索引必须唯一,否则报错
        // ImmutableMap<Integer, String> map = Maps.uniqueIndex(strs, new Function<String, Integer>() {
        // @Override
        // public Integer apply(String st) {
        // return st.length();
        // }
        // });
        // System.out.println(map);

        // ImmutableSet<String> set = ImmutableSet.of("aaa","bbb","c","dd","ee","ff","gg");
        // Function<String,Integer> function = new Function<String, Integer>() {
        // @Override
        // public Integer apply(String s) {
        // return s.length();
        // }
        // };
        // ImmutableListMultimap<Integer,String> list = Multimaps.index(set,function);
        // System.out.println(list);
        // 翻转映射
        // ArrayListMultimap<String,Integer> map = ArrayListMultimap.create();
        // map.putAll("a", Ints.asList(1,2,3));
        // map.putAll("b", Ints.asList(4,2,3));
        // map.putAll("c", Ints.asList(4,5,3));
        // TreeMultimap<Integer,String> inverse = Multimaps.invertFrom(map,TreeMultimap.<Integer, String>create());
        // System.out.println(inverse);

        // Map<String,Integer> map = ImmutableMap.of("a",1,"b",1,"c",2);
        // SetMultimap setMultimap = Multimaps.forMap(map);
        // Multimap<Integer,String> inverse = Multimaps.invertFrom(setMultimap, HashMultimap.create());
        // System.out.println(inverse);

        // Map<String,String> map = new HashMap<String,String>();
        // map.put("1", "b");
        // map.put("2","d");
        // String mapJoinResult = Joiner.on(",").withKeyValueSeparator("=").join(map);
        // System.out.println(mapJoinResult);
        // Joiner joiner = Joiner.on(",");
        // 下面报错
        // System.out.println(joiner.join("hank",null,"kun"));
        // 正常
        // Joiner joiner1 = Joiner.on(",").skipNulls();
        // System.out.println(joiner1.join("hank",null,"kun"));

        // String test = " ,a,,b,";
        // jdk正常模式
        // System.out.println(test.split(",").length);
        // System.out.println(Splitter.on(",").omitEmptyStrings().trimResults().split(test));

        // HashCode hashCode = Hashing.md5().newHasher().putString("name", Charsets.UTF_8).hash();
        // System.out.println(hashCode.hashCode());

        // TypeToken<Function<Integer, String>> funToken = new TypeToken<Function<Integer, String>>() {};
        //
        // TypeToken<?> funResultToken = funToken.resolveType(Function.class.getTypeParameters()[1]);
        // System.out.println(funResultToken.getType());

        // 读写文件
        // writeFile("first","hank is good");
        // readFile("first");
        // copyFile("first","second");

    }

    void writeFile(String name, String content) {
        File file = new File(name);
        try {
            Files.write(content.getBytes(), file);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    void readFile(String name) {
        File file = new File(name);
        System.out.println(Files.getNameWithoutExtension("first"));
        System.out.println(Files.getFileExtension("first.txt"));
        try {
            List<String> strings = Files.readLines(file, Charsets.UTF_8);
            System.out.println(strings);

        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    void copyFile(String src, String dest) {
        File srcFile = new File(src);
        File destFile = new File(dest);
        try {
            Files.copy(srcFile, destFile);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值