Guava Collections Cookbook – 番石榴收藏食谱

最后修改: 2013年 10月 23日

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

1. Introduction

1.介绍

This cookbook article is organized into small and focused recipes and code snippets for using Guava style collections.

这篇食谱文章被组织成小而集中的食谱和代码片断,用于使用Guava风格的集合。

The format is that of a growing list of code examples with no additional explanation necessary – it is meant to keep common usages of the API easy to access during development.

其格式是一个不断增长的代码示例列表,不需要额外的解释–其目的是在开发过程中保持API的常见用法易于访问。

2. The Recipes

2.菜谱

downcast a List<Parent> to a List<Child>

将一个List<Parent>下传到一个List<Child>

note: this is a workaround for non-covariant generified collections in Java

:这是对Java中的非变异生成集合的一种变通方法

class CastFunction<F, T extends F> implements Function<F, T> {
    @Override
    public final T apply(final F from) {
        return (T) from;
    }
}
List<TypeParent> originalList = Lists.newArrayList();
List<TypeChild> theList = Lists.transform(originalList, 
    new CastFunction<TypeParent, TypeChild>());

simpler alternative without Guava – involving 2 cast operations

没有Guava的更简单的替代方案–涉及2个铸造操作

List<Number> originalList = Lists.newArrayList();
List<Integer> theList = (List<Integer>) (List<? extends Number>) originalList;

adding an iterable to a collection

向一个集合添加一个可迭代的对象

Iterable<String> iter = Lists.newArrayList();
Collection<String> collector = Lists.newArrayList();
Iterables.addAll(collector, iter);

check if collection contains element(s) according to a custom matching rule

根据自定义匹配规则,检查集合是否包含元素

Iterable<String> theCollection = Lists.newArrayList("a", "bc", "def");
    boolean contains = Iterables.any(theCollection, new Predicate<String>() {
    @Override
    public boolean apply(final String input) {
        return input.length() == 1;
    }
});
assertTrue(contains);

alternative solution using search

使用搜索的替代解决方案

Iterable<String> theCollection = Sets.newHashSet("a", "bc", "def");
boolean contains = Iterables.find(theCollection, new Predicate<String>() {
    @Override
    public boolean apply(final String input) {
       return input.length() == 1;
    }
}) != null;
assertTrue(contains);

alternative solution only applicable to Sets

仅适用于集合的替代解决方案

Set<String> theCollection = Sets.newHashSet("a", "bc", "def");
boolean contains = !Sets.filter(theCollection, new Predicate<String>() {
    @Override
    public boolean apply(final String input) {
        return input.length() == 1;
    }
}).isEmpty();
assertTrue(contains);

NoSuchElementException on Iterables.find when nothing is found

NoSuchElementException on Iterables.find when nothing is found

Iterable<String> theCollection = Sets.newHashSet("abcd", "efgh", "ijkl");
Predicate<String> inputOfLengthOne = new Predicate<String>() {
    @Override
    public boolean apply(final String input) {
        return input.length() == 1;
    }
};
String found = Iterables.find(theCollection, inputOfLengthOne);

– this will throw the NoSuchElementException exception:

– 这将抛出NoSuchElementException异常

java.util.NoSuchElementException
	at com.google.common.collect.AbstractIterator.next(AbstractIterator.java:154)
	at com.google.common.collect.Iterators.find(Iterators.java:712)
	at com.google.common.collect.Iterables.find(Iterables.java:643)

solution: there is an overloaded find method that takes the default return value as an argument and can be called with null for the desired behavior:

解决方案:有一个重载的find方法,它将默认的返回值作为参数,可以用null来调用所需的行为。

String found = Iterables.find(theCollection, inputOfLengthOne, null);

remove all null values from a collection

从一个集合中删除所有空值

List<String> values = Lists.newArrayList("a", null, "b", "c");
Iterable<String> withoutNulls = Iterables.filter(values, Predicates.notNull());

create immutable List/Set/Map directly

直接创建不可变的List/Set/Map

ImmutableList<String> immutableList = ImmutableList.of("a", "b", "c");
ImmutableSet<String> immutableSet = ImmutableSet.of("a", "b", "c");
ImmutableMap<String, String> imuttableMap = 
    ImmutableMap.of("k1", "v1", "k2", "v2", "k3", "v3");

create immutable List/Set/Map from a standard collection

从一个标准集合中创建不可变的List/Set/Map

List<String> muttableList = Lists.newArrayList();
ImmutableList<String> immutableList = ImmutableList.copyOf(muttableList);

Set<String> muttableSet = Sets.newHashSet();
ImmutableSet<String> immutableSet = ImmutableSet.copyOf(muttableSet);

Map<String, String> muttableMap = Maps.newHashMap();
ImmutableMap<String, String> imuttableMap = ImmutableMap.copyOf(muttableMap);

alternative solution using builders

使用建设者的替代解决方案

List<String> muttableList = Lists.newArrayList();
ImmutableList<String> immutableList = 
    ImmutableList.<String> builder().addAll(muttableList).build();

Set<String> muttableSet = Sets.newHashSet();
ImmutableSet<String> immutableSet = 
    ImmutableSet.<String> builder().addAll(muttableSet).build();

Map<String, String> muttableMap = Maps.newHashMap();
ImmutableMap<String, String> imuttableMap = 
    ImmutableMap.<String, String> builder().putAll(muttableMap).build();

3. More Guava Cookbooks

3.更多的番石榴烹饪书

Guava is a comprehensive and fantastically useful library – here’s a few more APIs covered in cookbook form:

Guava是一个全面的、非常有用的库–这里还有一些以菜谱形式介绍的API。

Enjoy.

请享受。

4. Going Forward

4.前进

As I mentioned in the beginning, I am experimenting with this different format – the cookbook – to try to gather simple common tasks of using Guava Collections in a single place. The focus of this format is simplicity and speed, so most recipes have no additional explanation other than the code example itself.

正如我在一开始提到的,我正在尝试使用这种不同的格式–菜谱–来尝试将使用Guava集合的简单常用任务集中在一个地方。这种格式的重点是简单和快速,所以大多数菜谱除了代码例子本身外,没有其他解释。

Finally – I am looking at this as a living document – I’m going to keep adding recipes and examples as I run into them. Feel free to provide more in the comments and I’ll look to incorporate them into the cookbook.

最后–我把它看作是一份活的文件–我将不断增加我所遇到的食谱和例子。欢迎在评论中提供更多信息,我将寻求将它们纳入食谱中。

The implementation of all these examples and code snippets can be found over on GitHub – this is a Maven-based project, so it should be easy to import and run as it is.

所有这些例子和代码片段的实现都可以在GitHub上找到–这是一个基于Maven的项目,所以应该很容易导入并按原样运行。