google-collections让Java代码更简化 | GroovyQ
google-collections让Java代码更简化
由 huwh 于 二, 05/18/2010 - 08:49 发表
Groovy吸引人的地方是简洁流畅的语法,以及因之产生的高可读性。那么有办法让Java代码也变得更简化,更可读么?TheKaptain在博文给出了一个解决方法:google-collections,文中举出了google-collections的对Collection的简化方法。
创建Collection
Groovy的一个闪光点就是可以灵活的定义Collection,比如:List,map,空的Collection,不可变的Collection。但是在Java代码中,创建List还可以,但是创建Map就有点繁琐了,尤其是不可变的Map。这时就可以使用google-collections来简化代码。比如:
1 | import com.google.common.collect.ImmutableMap |
2 | Map<String, String> groovyMap = ["a":"1", "b":"2"].asImmutable() |
4 | Map<String, String> javaMap = new LinkedHashMap<String,String>() |
7 | javaMap = Collections.unmodifiableMap(javaMap) |
9 | Map<String, String> googleMap = ImmutableMap.of("a", "1", "b", "2") |
过滤Collection
Groovy中可以通过“findAll”执行闭包来过滤Collection。Google-collections也通过Predicate接口以及Collections2中的两个静态方法提供了类似的功能。示例代码如下:
01 | import static com.google.common.collect.Collections2.* |
02 | import com.google.common.base.Predicate |
03 | List<Integer> toFilter = [1, 2, 3, 4, 5] |
04 | List<Integer> groovyVersion = toFilter.findAll{ it < 3} |
05 | def googleVersion = filter(toFilter, new Predicate<Integer>() |
07 | public boolean apply(Integer input) |
用String连接Collection
对于Groovy中的List能够使用join将其中的元素连接起来。Google-collections则调用Joiner这个类达到了同样的效果。示例代码如下:
1 | import static com.google.common.base.Joiner.* |
2 | def toJoin = ['a', 'b', 'c'] |
6 | def groovyJoin = toJoin.join(separator) |
9 | def googleJoin = on(separator).join(toJoin) |
Google-collections还可以对Map进行连接,这个是Groovy中遗漏的内容。示例代码中给出了连接的三种方式,如下:
01 | import static com.google.common.base.Joiner.* |
02 | def toJoin = [1: 'a', 2: 'b', 3: 'c'] |
04 | def keyValueSeparator = ':' |
06 | def googleVersion = on(separator).withKeyValueSeparator(keyValueSeparator).join(toJoin) |
08 | googleVersion = on(" and ").withKeyValueSeparator(" is ").join(toJoin) |
10 | def groovyVersion = toJoin.inject([]) {builder, entry -> |
11 | builder << "${entry.key} is ${entry.value}" |
Multimap
你是否在纯Java中编写这样的代码:Map的元素值是一个List。还记得代码么?来看看使用Google-collections实现这样一个Map的代码:
3 | public boolean put(Object key, Object value) { |
4 | List list = map.get(key, []) |
Java代码是不是简单的许多?Google-collections和最新的Guava(含有Google-collections)还有许多简化代码的方法,比如对File、 Stream等的简化。如果你对降低Java代码量以及让代码更可读感兴趣,那就看看TheKaptain的原文吧!