在google code上,google列出了它的几个核心项目,这些项目涉及到collections, caching, primitives support, concurrency libraries, common annotations, basic string processing, I/O等等方面。
guava就是google在集合框架方面推出的扩展。
目前只是粗略地研究了一下,总得来说,这套api提供的功能不像apache common collections那样全面,但是却轻便灵活,很多api可以带来语法糖一样的便捷性。
看以下几个例子
首先是io方面
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(); } 直接省去了new FileReader(),很方便 |
再看看这个
FileInputStream in = null; try { in = new FileInputStream("/data/test.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); }finally{ Closeables.closeQuietly(in); }直接省去了try catch块 |
还可以把多个io数据源整合成一个
List<InputSupplier<? extends Reader>> list = new ArrayList<InputSupplier<? extends Reader>>(); InputSupplier<? extends Reader> is1 = new InputSupplier<FileReader>(){ @Override public FileReader getInput() throws IOException { return new FileReader("/data/f1"); } }; InputSupplier<? extends Reader> is2 = new InputSupplier<FileReader>(){ @Override public FileReader getInput() throws IOException { return new FileReader("/data/f2"); } }; list.add(is1); list.add(is2); MultiReader reader = new MultiReader(list.iterator()); char[] buffer = new char[1024]; reader.read(buffer,0,100);这下就可以从多个io源中读数据了 |
对基本类型的操作也提供了。当然这部分功能commons也有,但是guava的api更方便。
int[] array = { 1, 2, 3, 4, 5 }; int a = 4; boolean contains = Ints.contains(array, a); int indexOf = Ints.indexOf(array, a); int max = Ints.max(array); int min = Ints.min(array); int[] concat = Ints.concat(array, array2);直接把数组拼接。 |
当然还有最重头的,对collection的扩展
List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); list.add("d");可以这样写 ImmutableList<String> of = ImmutableList.of("a", "b", "c", "d");map也一样 Map<String,String> map = new Hasm<String,String>(); map.put("key1","value1"); map.put("key2","value2");可以代替 ImmutableMap<String,String> map = ImmutableMap.of("key1", "value1", "key2", "value2"); |
还有一些特别可爱的语法糖
Map<String,Map<String,? extends Reader>> map = Maps.newHashMap();Map<String,Map<String,? extends Reader>> map = Maps.newTreeMap();List<? extends Reader> list = Lists.newArrayList();List<? extends Reader> list = Lists.newLinkedList();直接省略了讨厌的泛形定义。很方便,其实这个原理很简单, public static <K, V> HashMap<K, V> newHashMap() { return new HashMap<K, V>(); }很常见的语法。springjdbc里的rowmapper就是这么传递泛形的。 |
综合来说,guava是一套非常轻便的api,虽然不像commons collection那样大而全,但是使用guava可以写出很优美的代码,也不失为一种好的选择。对于我们来说,特别有意义的一点在于,这套api代码量很小,便于学习,能够较快地让人掌握java的一些特性。
备注:
使用guava需引入jsr-305的实现。