Guava奇巧淫技

Guava是谷歌出品的Java工具类库,提供了字符串处理[string processing]、集合 [collections]、缓存[caching]、并发库[concurrency libraries]、I/O 等等实用的工具。JDK7之后很多API都是借鉴的Guava,说明Guava是非常优秀的。本文记录一些在我日常开发中用到的Guava技巧,用于提升工作效率,也欢迎大家的补充。

字符串操作-Splitter,Joiner

分割字符串

limit可以限制分割出的数组长度

List<String> list = Splitter.on(".")
                .trimResults()
                .omitEmptyStrings()
                .splitToList("aaa.bbb.ccc.. .ddd");

分割字符串获取最后一个子串

Iterables.getLast(Splitter.on(".").trimResults().split("aaa.bbb.ccc.. ccc.. .ddd"));

数组转字符串

List<String> strings = Lists.newArrayList("a", "b", null, "c");
Joiner.on("-").skipNulls().join(strings);

URL参数拼接

  • 优雅的拼接出id=1&name=java这样的URL参数

    Joiner.on("&").withKeyValueSeparator("=").join(ImmutableMap.of("id", 1, "name", "java"));
    

    获取URL参数的值

  • 轻松把URL参数的值转为Map

    Splitter.on("&").withKeyValueSeparator("=").split("id=1&name=java");
    

集合

创建不可变集合,三种方式

1.of方式

ImmutableMap<String, String> immutableMap = ImmutableMap.of("id", "1", "name", "guava");

2.copyOf方式

Map<String, String> map = new HashMap<>();
map.put("id", "1");
map.put("name", "guava");
ImmutableMap<String, String> immutableMap = ImmutableMap.copyOf(map);

3.builder模式

Map<String, String> map = new HashMap<>();
map.put("id", "1");
map.put("name", "guava");
ImmutableMap immutableMap = ImmutableMap.<String, String>builder()
                .putAll(map)
                .put("age", "20")
                .build();

集合的静态工厂方法

Lists

List<String> list = Lists.newArrayList();
List countUp = Ints.asList(1, 2, 3, 4, 5);
List countDown = Lists.reverse(countUp); // &#123;5, 4, 3, 2, 1&#125;
List<List> parts = Lists.partition(countUp, 2); // [[1, 2], [3, 4], [5]]

Maps

Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);
Map<String, Integer> right = ImmutableMap.of("d", 1, "b", 2, "f", 3);
MapDifference<String, Integer> diff = Maps.difference(left, right);
diff.entriesInCommon(); // &#123;b=2&#125;
diff.entriesOnlyOnLeft(); // &#123;a=1, c=3&#125;
diff.entriesOnlyOnRight(); // &#123;d=1, f=3&#125;

IO操作

byte[]转为InputStream

  • jdk
byte[] initialArray = &#123; 0, 1, 2 &#125;;
InputStream targetStream = new ByteArrayInputStream(initialArray);
  • guava
byte[] initialArray = &#123; 0, 1, 2 &#125;;
InputStream targetStream = ByteSource.wrap(initialArray).openStream();

InputStream转为byte[]

  • jdk
InputStream initialStream = new ByteArrayInputStream(new byte[] &#123; 0, 1, 2 &#125;);

byte[] targetArray = new byte[initialStream.available()];
initialStream.read(targetArray);
  • guava
InputStream initialStream = ByteSource.wrap(new byte[] &#123; 0, 1, 2 &#125;).openStream();

byte[] targetArray = ByteStreams.toByteArray(initialStream);

文件转换为流或字节数组

Guava Files类

//文件转换为输入流
InputStream inputStream = Files.asByteSource(file).openStream();
//文件转换为字节数组
byte[] buff = Files.asByteSource(file).read();

其他文件操作

Files.getNameWithoutExtension("/xxx/name.java");  //return name
Files.getFileExtension("/xxx/name.java");   //return java
//对文件hash,可自选算法
Files.asByteSource(file).hash(Hashing.md5());

前置条件

优雅地进行判断

Preconditions.checkNotNull(neme, "neme为null");

Preconditions.checkArgument(age>0, "age 必须大于0");

Preconditions.checkElementIndex(1, list.size());   // index>=0 && index<size

Preconditions.checkPositionIndex(1, list.size());  // index>=0 && index<=size

对象操作

JDK7之后的Objects类已经提供了这些方法,可以直接使用JDK的

Objects.equal("aaa", "bbb");

Objects.hashCode("aaa", "bbb");

反射

反射平时使用的较少,记录一个简化动态代理创建的方法

  • JDK方式
Proxy.newProxyInstance(User.class.getClassLoader(), new Class<?>[] &#123;User.class&#125;,
invocationHandler);
  • Guava方式非常简洁
Reflection.newProxy(User.class, invocationHandler);

结语

到这里就结束了,如果后面有实用的Guava技巧也会继续补充。个人总结,难免会有不准确的地方,欢迎大家指正和补充,共同进步。


   转载规则

本文不允许转载。
 上一篇
记一次向开源项目提交PR的过程 记一次向开源项目提交PR的过程
最近在做Electron+Vue的项目,这里用到了这个项目作为脚手架。然而,在准备打包生产环境配置,用于发布第一个正式版本的时候,发现把process.env.NODE_ENV设置为production并不能切换为生产环境的配置。 原
2018-08-08
下一篇 
SpringBoot+Vue.js前后端分离实现大文件分块上传 SpringBoot+Vue.js前后端分离实现大文件分块上传
原文地址: luoliangDSGA’s blog博客地址: https://luoliangdsga.github.io欢迎转载,转载请注明作者及出处,谢谢! SpringBoot+Vue.js前后端分离实现大文件分块上传 之前写
2018-06-25
  目录