有用的guava(一)

Google Guava是把小巧又锋利的瑞士军刀,把你的代码修剪得整洁又漂亮。
-------------尼古拉斯·沃兹基硕德java

1. Google Collections

咱们已经有Apache Commons Collections了,为何还须要另一个collections库呢?
由于好用呗!测试

平常编码中常常会遇到下面的代码:编码

Map<String, Map<String, String>> map = new HashMap<String, Map<String,String>>();

通过Guava的修剪后能够变成这样:code

Map<String, Map<String, String>> map = Maps.newHashMap();

甚至这样:对象

Table<String, String, String> tab = HashBaseTable.create();
//其实这种结构,就是一个二维映射,Guava把它包装成了table。
//还没完,变成这样后,访问起来比以前方便多了,直接拿两个维度去拿结果。
String res = tab.get("1", "1");

固然Lists和Sets也有这样的用法:
Lists.newArrayList();
Sets.newHashSet();get


有时候咱们须要一些测试数据构造一个不可变的List,通常都会这么写:io

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");

有了Guava能够这样:table

ImmutableList<String> of = ImmutableList.of("a", "b", "c", "d");

Map也同样List

ImmutableMap<String,String> map = ImmutableMap.of("key1", "value1", "key2", "value2");

有时候要用到双向映射,好比说根据学号查询名字和根据名字查询学号,这时候通常都须要建两个Map分别由学号映射到名字,由名字映射到学号。
但Guava的BiMap完美处理双向映射。file

BiMap<Integer,String> idNameMap = HashBiMap.create(); 
        idNameMap.put(1,"xiaohong");
        idNameMap.put(2,"xiaoming");
        idNameMap.put(3,"xiaolan"); 
        System.out.println("idNameMap:"+idNameMap); 
        BiMap<String,Integer> nameIdMap = idNameMap.inverse();
        System.out.println("nameIdMap:"+nameIdMap);

固然,在使用BiMap时,会要求Value的惟一性。若是value重复了则会抛出错误:java.lang.IllegalArgumentException。
inverse()会返回一个反转的BiMap,可是注意这个反转的map不是新的map对象,只是与原始map的一种关联,这样你对于反转后的map的全部操做都会影响原始的map对象。

2. 文件操做

为了从文件中读取内容通常操做以下:

File file = new File(getClass().getResource("/aaa.txt").getFile());
BufferedReader reader;
String text = "";
try {
    reader = new BufferedReader(new FileReader(file));
    String line = null;
    while (true) {
        line = reader.readLine();
        if (line == null) {
            break;
        }
        text += line.trim() + "\n";
    }
    reader.close();
    reader = null;
} catch (FileNotFoundException e1) {
    e1.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Guava看了以后说:太长了,看个人:

File file = new File(getClass().getResource("/aaa.txt").getFile());
List<String> lines = null;
try {
  lines = Files.readLines(file, Charsets.UTF_8);
} catch (IOException e) {
  e.printStackTrace();
}

整个世界清静了!

未完待续···

相关文章
相关标签/搜索