googlecollections让Java代码更简化 | GroovyQ

google-collections让Java代码更简化 | GroovyQ

google-collections让Java代码更简化

Groovy吸引人的地方是简洁流畅的语法,以及因之产生的高可读性。那么有办法让Java代码也变得更简化,更可读么?TheKaptain在博文给出了一个解决方法:google-collections,文中举出了google-collections的对Collection的简化方法。

创建Collection

Groovy的一个闪光点就是可以灵活的定义Collection,比如:List,map,空的Collection,不可变的Collection。但是在Java代码中,创建List还可以,但是创建Map就有点繁琐了,尤其是不可变的Map。这时就可以使用google-collections来简化代码。比如:

1import com.google.common.collect.ImmutableMap
2Map<String, String> groovyMap = ["a":"1", "b":"2"].asImmutable()
3 
4Map<String, String> javaMap = new LinkedHashMap<String,String>()
5javaMap.put("a", "1")
6javaMap.put("b", "2")
7javaMap = Collections.unmodifiableMap(javaMap)
8 
9Map<String, String> googleMap = ImmutableMap.of("a", "1", "b", "2")

过滤Collection

Groovy中可以通过“findAll”执行闭包来过滤Collection。Google-collections也通过Predicate接口以及Collections2中的两个静态方法提供了类似的功能。示例代码如下:

01import static com.google.common.collect.Collections2.*
02import com.google.common.base.Predicate
03List<Integer> toFilter = [1, 2, 3, 4, 5]
04List<Integer> groovyVersion = toFilter.findAll{ it < 3}
05def googleVersion = filter(toFilter, new Predicate<Integer>()
06    {
07        public boolean apply(Integer input)
08        {
09            return input < 3;
10        }
11    })

用String连接Collection

对于Groovy中的List能够使用join将其中的元素连接起来。Google-collections则调用Joiner这个类达到了同样的效果。示例代码如下:

1import static com.google.common.base.Joiner.*
2def toJoin = ['a', 'b', 'c']
3def separator = ', '
4 
5//groovy version
6def groovyJoin = toJoin.join(separator)
7 
8//google-collections version
9def googleJoin = on(separator).join(toJoin)

Google-collections还可以对Map进行连接,这个是Groovy中遗漏的内容。示例代码中给出了连接的三种方式,如下:

01import static com.google.common.base.Joiner.*
02def toJoin = [1: 'a', 2: 'b', 3: 'c']
03def separator = ', '
04def keyValueSeparator = ':'
05 
06def googleVersion = on(separator).withKeyValueSeparator(keyValueSeparator).join(toJoin)
07 
08googleVersion = on(" and ").withKeyValueSeparator(" is ").join(toJoin)
09 
10def groovyVersion = toJoin.inject([]) {builder, entry ->
11            builder << "${entry.key} is ${entry.value}"
12        }.join(' and ')

Multimap

你是否在纯Java中编写这样的代码:Map的元素值是一个List。还记得代码么?来看看使用Google-collections实现这样一个Map的代码:

1class GroovyMultimap{
2    Map map = [:]
3    public boolean put(Object key, Object value)    {
4        List list = map.get(key, [])
5        list.add(value)
6        map."$key" = list
7    }
8}

Java代码是不是简单的许多?Google-collections和最新的Guava(含有Google-collections)还有许多简化代码的方法,比如对File、 Stream等的简化。如果你对降低Java代码量以及让代码更可读感兴趣,那就看看TheKaptain的原文吧!

原文地址:https://www.cnblogs.com/lexus/p/2558921.html