Guava 19: What’s New? – Guava 19: What’s New?

最后修改: 2016年 2月 9日


1. Overview


Google Guava provides libraries with utilities that ease Java development. In this tutorial we will take a look to new functionality introduced in the Guava 19 release.

Google Guava提供了带有实用程序的库,以简化Java开发。在本教程中,我们将了解一下Guava 19版本中引入的新功能。

2. common.base Package Changes


2.1. Added CharMatcher Static Methods

2.1.增加了CharMatcher 静态方法

CharMatcher, as its name implies, is used to check whether a string matches a set of requirements.


String inputString = "someString789";
boolean result = CharMatcher.javaLetterOrDigit().matchesAllOf(inputString);

In the example above, result will be true.


CharMatcher can also be used when you need to transform strings.


String number = "8 123 456 123";
String result = CharMatcher.whitespace().collapseFrom(number, '-');

In the example above, result will be “8-123-456-123”.

在上面的例子中,result将是 “8-123-456-123″。

With the help of CharMatcher, you can count the number of occurrences of a character in a given string:


String number = "8 123 456 123";
int result = CharMatcher.digit().countIn(number);

In the example above, result will be 10.


Previous versions of Guava have matcher constants such as CharMatcher.WHITESPACE and CharMatcher.JAVA_LETTER_OR_DIGIT.


In Guava 19, these have been superseded by equivalent methods (CharMatcher.whitespace() and CharMatcher.javaLetterOrDigit(), respectively). This was changed to reduce the number of classes created when CharMatcher is used.

在Guava 19中,这些方法已经被同等的方法(CharMatcher.whitespace()CharMatcher.javaLetterOrDigit(),分别)取代了。这样的改变是为了减少在使用CharMatcher时创建的类的数量。

Using static factory methods allows classes to be created only as needed. In future releases, matcher constants will be deprecated and removed.


2.2. lazyStackTrace Method in Throwables

2.2. lazyStackTrace Throwables中的方法

This method returns a List of stacktrace elements (lines) of a provided Throwable. It can be faster than iterating through the full stacktrace (Throwable.getStackTrace()) if only a portion is needed, but can be slower if you will iterate over the full stacktrace.


IllegalArgumentException e = new IllegalArgumentException("Some argument is incorrect");
List<StackTraceElement> stackTraceElements = Throwables.lazyStackTrace(e);

3. common.collect Package Changes


3.1. Added FluentIterable.toMultiset()


In a previous Baeldung article, Whats new in Guava 18, we looked at FluentIterable. The toMultiset() method is used when you need to convert a FluentIterable to an ImmutableMultiSet.

在之前的Baeldung文章Guava 18的新内容中,我们研究了FluentIterable。当你需要将FluentIterable转换为ImmutableMultiSet时,可以使用toMultiset()方法。

User[] usersArray = {new User(1L, "John", 45), new User(2L, "Max", 15)};
ImmutableMultiset<User> users = FluentIterable.of(usersArray).toMultiset();

A Multiset is collection, like Set, that supports order-independent equality. The main difference between a Set and a Multiset is that Multiset may contain duplicate elements. Multiset stores equal elements as occurrences of the same single element, so you can call Multiset.count(java.lang.Object) to get the total count of occurrences of a given object.


Lets take a look to few examples:


List<String> userNames = Arrays.asList("David", "Eugen", "Alex", "Alex", "David", "David", "David");

Multiset<String> userNamesMultiset = HashMultiset.create(userNames);

assertEquals(7, userNamesMultiset.size());
assertEquals(4, userNamesMultiset.count("David"));
assertEquals(2, userNamesMultiset.count("Alex"));
assertEquals(1, userNamesMultiset.count("Eugen"));
assertThat(userNamesMultiset.elementSet(), anyOf(containsInAnyOrder("Alex", "David", "Eugen")));

You can easily determine the count of duplicate elements, which is far cleaner than with standard Java collections.


3.2. Added RangeSet.asDescendingSetOfRanges() and asDescendingMapOfRanges()


RangeSet is used to operate with nonempty ranges (intervals). We can describe a RangeSet as a set of disconnected, nonempty ranges. When you add a new nonempty range to a RangeSet, any connected ranges will be merged and empty ranges will be ignored:


Let’s take a look at some methods we can use to build new ranges: Range.closed(), Range.openClosed(), Range.closedOpen(),

让我们看一下我们可以用来建立新范围的一些方法。Range.closed(), Range.openClosed(), Range.closedOpen(),

The difference between them is that open ranges don’t include their endpoints. They have different designation in mathematics. Open intervals are denoted with “(” or “)”, while closed ranges are denoted with “[” or “]”.


For example (0,5) means “any value greater than 0 and less than 5”, while (0,5] means “any value greater than 0 and less than or equal to 5”:

例如,(0,5)意味着 “任何大于0且小于5的值”,而(0,5)意味着 “任何大于0且小于或等于5的值”。

RangeSet<Integer> rangeSet = TreeRangeSet.create();
rangeSet.add(Range.closed(1, 10));

Here we added range [1, 10] to our RangeSet. And now we want to extend it by adding new range:

在这里,我们在我们的RangeSet中添加了范围[1, 10]。现在我们想通过添加新的范围来扩展它。

rangeSet.add(Range.closed(5, 15));

You can see that these two ranges are connected at 5, so RangeSet will merge them to a new single range, [1, 15]:

你可以看到这两个范围在5处相连,所以RangeSet将把它们合并为一个新的单一范围,[1, 15]。

rangeSet.add(Range.closedOpen(10, 17));

These ranges are connected at 10, so they will be merged, resulting in a closed-open range, [1, 17). You can check if a value included in range or not using the contains method:

这些范围在10处相连,所以它们将被合并,产生一个封闭-开放的范围,[1, 17]。你可以使用contains方法检查一个值是否包含在范围内。


This will return true, because the range [1,17) contains 15. Let’s try another value:



This will return false, because range [1,17) doesn’t contain it’s upper endpoint, 17. You can also check if range encloses any other range using the encloses method:


rangeSet.encloses(Range.closed(2, 3));

This will return true because the range [2,3] falls completely within our range, [1,17).


There are a few more methods that can help you operate with intervals, such as Range.greaterThan(), Range.lessThan(), Range.atLeast(), Range.atMost(). The first two will add open intervals, the last two will add closed intervals. For example:

还有一些方法可以帮助你对区间进行操作,比如Range.grandThan(), Range.lessThan(), Range.atLeast(), Range.atMost()。前两个将添加开放区间,后两个将添加封闭区间。比如说。


This will add a new interval (22, +∞) to your RangeSet, because it has no connections with other intervals.

这将在你的RangeSet中添加一个新的区间(22, +∞),因为它与其他区间没有联系。

With the help of new methods such as asDescendingSetOfRanges (for RangeSet) and asDescendingMapOfRanges (for RangeSet) you can convert a RangeSet to a Set or Map.


3.3. Added Lists.cartesianProduct(List…) and Lists.cartesianProduct(List<List>>)


A Cartesian product returns every possible combination of two or more collections:


List<String> first = Lists.newArrayList("value1", "value2");
List<String> second = Lists.newArrayList("value3", "value4");

List<List<String>> cartesianProduct = Lists.cartesianProduct(first, second);

List<String> pair1 = Lists.newArrayList("value2", "value3");
List<String> pair2 = Lists.newArrayList("value2", "value4");
List<String> pair3 = Lists.newArrayList("value1", "value3");
List<String> pair4 = Lists.newArrayList("value1", "value4");

assertThat(cartesianProduct, anyOf(containsInAnyOrder(pair1, pair2, pair3, pair4)));

As you can see from this example, the resulting list will contain all possible combinations of provided lists.


3.4. Added Maps.newLinkedHashMapWithExpectedSize(int)


The initial size of a standard LinkedHashMap is 16 (you can verify this in the source of LinkedHashMap). When it reaches the load factor of HashMap (by default, 0.75), HashMap will rehash and double it size. But if you know that your HashMap will handle many key-value pairs, you can specify an initial size greater then 16, allowing you to avoid repeated rehashings:


LinkedHashMap<Object, Object> someLinkedMap = Maps.newLinkedHashMapWithExpectedSize(512);

3.5. Re-added Multisets.removeOccurrences(Multiset, Multiset)

3.5.重新添加Multisets.removeOccurrences(Multiset, Multiset)

This method is used to remove specified occurrences in Multiset:


Multiset<String> multisetToModify = HashMultiset.create();
Multiset<String> occurrencesToRemove = HashMultiset.create();



Multisets.removeOccurrences(multisetToModify, occurrencesToRemove);

After this operation only “Max” will be left in multisetToModify.

此操作后,multisetToModify中只剩下 “Max”。

Note that, if multisetToModify contained multiple instances of a given element while occurrencesToRemove contains only one instance of that element, removeOccurrences will only remove one instance.

请注意,如果 multisetToModify 包含某个元素的多个实例,而 occurrencesToRemove 只包含该元素的一个实例,removeOccurrences 将只删除一个实例。

4. common.hash Package Changes


4.1. Added Hashing.sha384()


The Hashing.sha384() method returns a hash function that implements the SHA-384 algorithm:

Hashing.sha384() 方法返回一个实现SHA-384算法的哈希函数。

int inputData = 15;
HashFunction hashFunction = Hashing.sha384();
HashCode hashCode = hashFunction.hashInt(inputData);

The SHA-384 has for 15 is “0904b6277381dcfbddd…2240a621b2b5e3cda8”.

15的SHA-384是 “0904b6277381dcfbddd…2240a621b2b5e3cda8″。

4.2. Added Hashing.concatenating(HashFunction, HashFunction, HashFunction…) and Hashing.concatenating(Iterable<HashFunction>)

4.2.添加了Hashing.concatenating(HashFunction, HashFunction, HashFunction…)Hashing.concatenating(Iterable<HashFunction>)/strong>。

With help of the Hashing.concatenating methods, you concatenate the results of a series of hash functions:


int inputData = 15;

HashFunction crc32Function = Hashing.crc32();
HashCode crc32HashCode = crc32Function.hashInt(inputData);

HashFunction hashFunction = Hashing.concatenating(Hashing.crc32(), Hashing.crc32());
HashCode concatenatedHashCode = hashFunction.hashInt(inputData);

The resulting concatenatedHashCode will be “4acf27794acf2779”, which is the same as the crc32HashCode (“4acf2779”) concatenated with itself.

产生的concatenatedHashCode将是 “4acf27794acf2779″,这与crc32HashCode(”4acf2779″)与自身相连接是一样的。

In our example, a single hashing algorithm was used for clarity. This is not particularly useful, however. Combining two hash functions is useful when you need to make your hash stronger, as it can only be broken if two of your hashes are broken. For most cases, use two different hash functions.


5. common.reflect Package Changes


5.1. Added TypeToken.isSubtypeOf


TypeToken is used to manipulate and query generic types even in runtime, avoiding problems due to type erasure.


Java doesn’t retain generic type information for objects at runtime, so it is impossible to know if a given object has a generic type or not. But with the assistance of reflection, you can detect generic types of methods or classes. TypeToken uses this workaround to allow you to work with and query generic types without extra code.


In our example, you can see that, without the TypeToken method isAssignableFrom, will return true even though ArrayList<String> is not assignable from ArrayList<Integer>:


ArrayList<String> stringList = new ArrayList<>();
ArrayList<Integer> intList = new ArrayList<>();
boolean isAssignableFrom = stringList.getClass().isAssignableFrom(intList.getClass());

To solve this problem, we can check this with the help of TypeToken.


TypeToken<ArrayList<String>> listString = new TypeToken<ArrayList<String>>() { };
TypeToken<ArrayList<Integer>> integerString = new TypeToken<ArrayList<Integer>>() { };

boolean isSupertypeOf = listString.isSupertypeOf(integerString);

In this example, isSupertypeOf will return false.


In previous versions of Guava there was method isAssignableFrom for this purposes, but as of Guava 19, it is deprecated in favor of isSupertypeOf. Additionally, the method isSubtypeOf(TypeToken) can be used to determine if a class is a subtype of another class:

在以前的Guava版本中,有方法isAssignableFrom用于此目的,但从Guava 19开始,它已被废弃,而改为isSupertypeOf。此外,方法isSubtypeOf(TypeToken) 可以用来确定一个类是否是另一个类的子类型。

TypeToken<ArrayList<String>> stringList = new TypeToken<ArrayList<String>>() { };
TypeToken<List> list = new TypeToken<List>() { };

boolean isSubtypeOf = stringList.isSubtypeOf(list);

ArrayList is a subtype of List, so the result will be true, as expected.


6. Package Changes


6.1. Added ByteSource.sizeIfKnown()


This method returns the size of the source in bytes, if it can be determined, without opening the data stream:


ByteSource charSource = Files.asByteSource(file);
Optional<Long> size = charSource.sizeIfKnown();

6.2. Added CharSource.length()


In previous version of Guava there was no method to determine the length of a CharSource. Now you can use CharSource.length() for this purpose.


6.3. Added CharSource.lengthIfKnown()


The same as for ByteSource, but with CharSource.lengthIfKnown() you can determine length of your file in characters:


CharSource charSource = Files.asCharSource(file, Charsets.UTF_8);
Optional<Long> length = charSource.lengthIfKnown();

7. Conclusion


Guava 19 introduced many useful additions and improvements to its growing library. It is well-worth considering for use in your next project.

Guava 19为其不断增长的库引入了许多有用的补充和改进。它非常值得考虑在你的下一个项目中使用。

The code samples in this article are available in the GitHub repository.