Guava Collections Cookbook
1. introduction
Cet article de livre de cuisine est organisé ensmall and focused recipes and code snippets pour l'utilisation des collections de style Guava.
Le format est celui dea growing list of code examples sans aucune explication supplémentaire nécessaire - il est destiné à faciliter l'accès aux utilisations courantes de l'API pendant le développement.
2. Les recettes
downcast un List
-note: il s'agit d'une solution de contournement pour les collections générées non covariantes en 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());
alternative plus simple sans Guava - impliquant 2 opérations de cast
List originalList = Lists.newArrayList();
List theList = (List) (List extends Number>) originalList;
ajouter un itérable à une collection
Iterable iter = Lists.newArrayList();
Collection collector = Lists.newArrayList();
Iterables.addAll(collector, iter);
vérifier si la collection contient des éléments selon une règle de correspondance personnalisée
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);
solution alternative utilisant la recherche
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);
solution alternative uniquement applicable aux ensembles
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 surIterables.find lorsque rien n'est trouvé
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);
- cela lancerathe 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: il y aan overloaded find method qui prend la valeur de retour par défaut comme argument et peut être appelée avecnull pour le comportement souhaité:
String found = Iterables.find(theCollection, inputOfLengthOne, null);
supprimer toutes les valeurs nulles d'une collection
List values = Lists.newArrayList("a", null, "b", "c");
Iterable withoutNulls = Iterables.filter(values, Predicates.notNull());
créer directement une liste / un ensemble / une carte immuable
ImmutableList immutableList = ImmutableList.of("a", "b", "c");
ImmutableSet immutableSet = ImmutableSet.of("a", "b", "c");
ImmutableMap imuttableMap =
ImmutableMap.of("k1", "v1", "k2", "v2", "k3", "v3");
créer une liste / un ensemble / une carte immuable à partir d'une collection standard
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);
solution alternative utilisant des constructeurs
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. Plus de livres de cuisine sur la goyave
Guava est une bibliothèque complète et extrêmement utile. Voici quelques API supplémentaires couvertes sous forme de livre de recettes:
Prendre plaisir.
4. Aller de l'avant
Comme je l'ai mentionné au début, j'expérimente avec cedifferent format – the cookbook - pour essayer de rassembler des tâches courantes simples d'utilisation des collections de goyaves en un seul endroit. L'objectif de ce format est la simplicité et la rapidité, de sorte que la plupart des recettes ont desno additional explanation other than the code example itself.
Enfin - je regarde cela commea living document - je vais continuer à ajouter des recettes et des exemples au fur et à mesure que je les rencontre. N'hésitez pas à en fournir plus dans les commentaires et je chercherai à les intégrer dans le livre de recettes.
L'implémentation de tous ces exemples et extraits de codecan be found over on GitHub - il s'agit d'un projet basé sur Maven, il devrait donc être facile à importer et à exécuter tel quel.