Livro de receitas das coleções da goiaba

Livro de receitas das coleções da goiaba

1. Introdução

Este artigo do livro de receitas está organizado emsmall and focused recipes and code snippets para usar coleções de estilo Guava.

O formato é o dea growing list of code examples sem nenhuma explicação adicional necessária - o objetivo é manter os usos comuns da API fáceis de acessar durante o desenvolvimento.

2. As receitas

downcast de uma Lista para uma Lista

-note: esta é uma solução alternativa para coleções geradas não covariantes em Java **

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

alternativa mais simples sem goiaba - envolvendo 2 operações de elenco

List originalList = Lists.newArrayList();
List theList = (List) (List) originalList;

adicionar um iterável a uma coleção

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

verifique se a coleção contém elemento (s) de acordo com uma regra de correspondência personalizada

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

solução alternativa usando pesquisa

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

solução alternativa aplicável apenas a conjuntos

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

NoSuchElementException emIterables.find quando nada é encontrado

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

- isso geraráthe NoSuchElementException exception:

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: háan overloaded find method que leva o valor de retorno padrão como um argumento e pode ser chamado comnull para o comportamento desejado:

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

remove todos os valores nulos de uma coleção

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

criar lista / conjunto / mapa imutável diretamente

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

criar Lista / Conjunto / Mapa imutável de uma coleção padrão

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

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

Map muttableMap = Maps.newHashMap();
ImmutableMap imuttableMap = ImmutableMap.copyOf(muttableMap);

solução alternativa usando construtores

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

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

Map muttableMap = Maps.newHashMap();
ImmutableMap imuttableMap =
    ImmutableMap. builder().putAll(muttableMap).build();

3. Mais livros de receitas de goiaba

Guava é uma biblioteca abrangente e fantasticamente útil - aqui estão mais algumas APIs abordadas na forma de livro de receitas:

Desfrutar.

4. Daqui para frente

Como mencionei no início, estou experimentando estedifferent format – the cookbook - para tentar reunir tarefas comuns simples de usar coleções de goiaba em um único lugar. O foco desse formato é a simplicidade e a velocidade, portanto, a maioria das receitas temno additional explanation other than the code example itself.

Finalmente - estou vendo isso comoa living document - vou continuar adicionando receitas e exemplos enquanto os encontro. Fique à vontade para fornecer mais nos comentários e tentarei incorporá-los ao livro de receitas.

A implementação de todos esses exemplos e trechos de códigocan be found over on GitHub - este é um projeto baseado em Maven, portanto, deve ser fácil de importar e executar como está.