有用的guava(一)

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

1. Google Collections

我们已经有Apache Commons Collections了,为什么还需要另外一个collections库呢?
因为好用呗!

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

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

经过Guava的修剪后可以变成这样:

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();


有时候我们需要一些测试数据构造一个不可变的List,一般都会这么写:

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

有了Guava可以这样:

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

Map也一样

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

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

        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();
}

整个世界清静了!

未完待续···

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值