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

最后修改: 2016年 2月 9日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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.common.base包变化

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.

CharMatcher,顾名思义,是用来检查一个字符串是否符合一组要求。

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

In the example above, result will be true.

在上面的例子中,result将是true

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

CharMatcher也可以在你需要转换字符串时使用。

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:

CharMatcher的帮助下,你可以计算一个字符在给定字符串中出现的次数。

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

In the example above, result will be 10.

在上面的例子中,result将是10。

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

先前版本的Guava有一些匹配器常量,如CharMatcher.WHITESPACECharMatcher.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.

该方法返回所提供的Throwable的堆栈跟踪元素(行)的List。如果只需要一部分,它可能比迭代整个堆栈跟踪(Throwable.getStackTrace())更快,但如果你将迭代整个堆栈跟踪,则可能更慢。

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

3. common.collect Package Changes

3.common.collect包的变化

3.1. Added FluentIterable.toMultiset()

3.1.增加了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.

Multiset是一个集合,像Set一样,支持与顺序无关的平等。SetMultiset之间的主要区别是,Multiset可能包含重复的元素。Multiset将相等的元素存储为相同的单一元素的出现,所以你可以调用Multiset.count(java.lang.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.

你可以很容易地确定重复元素的数量,这要比标准的Java集合干净得多。

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

3.2.添加了RangeSet.asDescendingSetOfRanges()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:

RangeSet用于操作非空的范围(区间)。我们可以将RangeSet描述为一组不相连的、非空的范围。当你向RangeSet添加一个新的非空范围时,任何连接的范围将被合并,空范围将被忽略。

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

让我们看一下我们可以用来建立新范围的一些方法。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”:

例如,(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方法检查一个值是否包含在范围内。

rangeSet.contains(15);

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

这将返回true,因为范围[1,17]包含15。让我们试试另一个值。

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:

这将返回false,因为范围[1,17]不包含它的上端点,17。你也可以使用encloses方法来检查范围是否包含任何其他范围。

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

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

这将返回true,因为范围[2,3]完全在我们的范围内,[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()。前两个将添加开放区间,后两个将添加封闭区间。比如说。

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

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.

在新方法的帮助下,如asDescendingSetOfRanges(针对RangeSet)和asDescendingMapOfRanges(针对RangeSet),你可以将RangeSet转换为SetMap

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

3.3.增加了Lists.cartesianProduct(List…)Lists.cartesianProduct(List<List>>)/strong>。

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)

3.4.增加了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的初始大小是16(你可以在LinkedHashMap的源代码中验证这一点)。当它达到HashMap的负载系数时(默认为0.75),HashMap将重新洗牌并将其大小翻倍。但是如果你知道你的HashMap将处理许多键值对,你可以指定一个大于16的初始大小,让你避免重复洗练。

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中的指定出现。

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.

此操作后,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.common.hash软件包变化

4.1. Added Hashing.sha384()

4.1.增加了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:

Hashing.concatenating方法的帮助下,你可以将一系列哈希函数的结果连接起来。

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.common.reflect包的变化

5.1. Added TypeToken.isSubtypeOf

5.1.增加了TypeToken.isSubtypeOf

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

TypeToken甚至在运行时也用于操作和查询通用类型,避免了由于类型擦除而产生的问题

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.

Java在运行时并不保留对象的通用类型信息,所以不可能知道某个对象是否有通用类型。但在反射的帮助下,你可以检测方法或类的通用类型。TypeToken使用了这种变通方法,使你能够在没有额外代码的情况下处理和查询通用类型。

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

在我们的例子中,你可以看到,如果没有TypeToken方法isAssignableFrom,将返回true,即使ArrayList<String>不能从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的帮助下检查。

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.

在这个例子中,isSupertypeOf将返回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.

ArrayListList的一个子类型,所以结果将是true,正如预期。

6. common.io Package Changes

6.common.io包的变化

6.1. Added ByteSource.sizeIfKnown()

6.1.增加了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()

6.2.增加了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.

在Guava的前一个版本中,没有方法来确定CharSource的长度。现在你可以使用CharSource.length()来达到这个目的。

6.3. Added CharSource.lengthIfKnown()

6.3.增加了CharSource.lengthIfKnown()

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

ByteSource相同,但通过CharSource.lengthIfKnown()你可以确定你的文件的长度,以字符为单位。

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

7. Conclusion

7.结论

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.

本文中的代码样本可在GitHub资源库中获得。