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.

2. common.base Package Changes

2.1. Added CharMatcher Static Methods

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”.

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.

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

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.

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.open().

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”:

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.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]:

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:

rangeSet.contains(15);

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

rangeSet.contains(17);

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:

rangeSet.add(Range.greaterThan(22));

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

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>)

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)

This method is used to remove specified occurrences in Multiset:

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

multisetToModify.add("John");
multisetToModify.add("Max");
multisetToModify.add("Alex");

occurrencesToRemove.add("Alex");
occurrencesToRemove.add("John");

Multisets.removeOccurrences(multisetToModify, occurrencesToRemove);

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

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.

4. common.hash Package Changes

4.1. Added Hashing.sha384()

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

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

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

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

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.

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 is not assignable from ArrayList:

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:

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. common.io 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.

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


» 下一篇: RESTEasy指南