Google guava工具类的介绍和使用

概述

Guava,中文是石榴的意思,一个基于JDK1.6类库集合的扩展项目。这个库能简化你的代码,使它易写、易读、易于维护。它能提高你的工作效率,让你从大量重复的底层代码中脱身,让你的代码更加简洁。

浅尝

以往都是这么写代码的:

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

或者这样:

int temp_a = 10;
int temp_b = 10;
int compareTo=Integer.valueOf(a).compareTo(Integer.valueOf(b));

又或者是为了写单元测试时,经常会构造一些测试数据,可能是list、map、set,然后这样写:

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

现在可以这么写:

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

ImmutableList<String> list2 = listOf("a", "b", "c", "d");

构造填充一个ArrayList(或者一个HashMap),可以这样:

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

guava提供了很多额外的工具方法,比如过滤,对set取交集和并集,排序等等一些更优雅的方法。

不可变集合

先理解什么是immutable(不可变)对象
在多线程操作下,是线程安全的。
所有不可变集合会比可变集合更有效的利用资源。
中途不可改变
创建集合
Guava创建的集合是由静态工厂创建的,所以比普通的集合更省资源

普通Collection的创建

List<String> list = Lists.newArrayList();
Set<String> set = Sets.newHashSet();
Map<String, String> map = Maps.newHashMap();

不变Collection的创建

ImmutableList<String> iList =ImmutableList.of("a", "b", "c");
ImmutableSet<String> iSet =ImmutableSet.of("e1", "e2");
ImmutableMap<String, String> iMap =ImmutableMap.of("k1", "v1", "k2","v2");

当我们需要一个map中包含key为String value为List类型的时候以前我们是这样写的

Map<String,List<Integer>> map = new HashMap<String,List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
map.put("test", list);
System.out.println(map.get("test"));//[10, 20]

而现在

Multimap<String,Integer> map = ArrayListMultimap.create();
map.put("test", 10); 
map.put("test", 20); 
System.out.println(map.get("test")); //[10, 20]

将集合转换为特定规则的字符串
以前我们将list转换为特定规则的字符串是这样写的:

List<String> list = new ArrayList<String>();
list.add("aa");
list.add("bb");
list.add("cc");
String str = "";
for(int i=0; i<list.size(); i++){
    str = str + "-" +list.get(i);
}

使用guava前:

List<String> list = new ArrayList<String>();
list.add("aa");

list.add("bb");
list.add("cc");
String result = Joiner.on("-").join(list); //result为 aa-bb-cc
将String转换为特定的集合
//use java
List<String> list = new ArrayList<String>();
String a = "1-2-3-4-5-6";
String[] strs = a.split("-");
for(int i=0; i<strs.length; i++){
    list.add(strs[i]);
}

使用guava后:

//use guava
String str = "1-2-3-4-5-6";
List<String> list =
Splitter.on("-").splitToList(str);
//list为 [1, 2, 3, 4, 5, 6]

强大的String类

仅作简单介绍

System.out.println(Strings.isNullOrEmpty(""));//true
System.out.println(Strings.nullToEmpty(null));//""
System.out.println(Strings.nullToEmpty("ay"));//"ay"
System.out.println(Strings.emptyToNull(""));//null
System.out.println(Strings.emptyToNull("ay"));//"ay"
System.out.println(Strings.commonPrefix("aaay","aal"));//"aa"否则返回""
System.out.println(Strings.commonSuffix("aaay","aal"));//"aac"否则返回""
String str1 = "ay.";
//在str1后补'a'补够15个长度
String strr1 = Strings.padEnd(str1,15,'l');
System.out.println(strr1);//ay.llllllllllll
//在str2前补'a'补够10个长度
String str2 = "welcome";
String strr2 = Strings.padStart(str2, 10, 'm');
System.out.println(strr2);

好用的Object方法

Objects.equal("a","a"); // returns true
Objects.equal(null, "a"); //returns false
Objects.equal("a", null); //returns false
Objects.equal(null, null); // returns true

Guava I/O流

以前的写法

File file = new File(getClass().getResource("/test.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();
}

现在可以这么写:

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

更多好用的等待你去挖掘……

备注:个人博客同步至简书。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,246评论 0 38
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,916评论 0 13
  • 端坐在台灯下,书桌前,挤出一点点时间,练几个字宽慰一下自己,却无意中摹到:“落叶他乡树,寒灯独夜人”,教我如何移得...
    忙着变强来不及沮丧阅读 255评论 0 0
  • 一周看房经历磨灭了我的积极性,呵呵,好的地段根本不用看,动不动几百万的,偏点的吧,单价相对低点,但是交通太不方便,...
    郑喻心阅读 311评论 0 0
  • 春节还未走远,在鸡鸭鱼肉的油腻中,两股清流乘着新年的第一缕春风,火遍了朋友圈——赵雷和武亦姝。 赵雷在《歌手》第三...
    影评空间阅读 1,673评论 3 14

友情链接更多精彩内容