Recherche…


Remarques

Ce sujet sur les collections Java à partir de guava, apache, eclipse: Multiset, Bag, Multimap, utils fonctionne à partir de cette lib, etc.

Apache HashBag, Guava HashMultiset et Eclipse HashBag

Un bag / ultiset stocke chaque objet de la collection avec un nombre d'occurrences. Des méthodes supplémentaires sur l'interface permettent à plusieurs copies d'un objet d'être ajoutées ou supprimées à la fois. JDK analog est HashMap <T, Integer>, lorsque les valeurs sont le nombre de copies de cette clé.

Type Goyave Collections Apache Commons Collections GS JDK
Ordre non défini HashMultiset HashBag HashBag HashMap
Trié TreeMultiset TreeBag TreeBag TreeMap
Ordre d'insertion LinkedHashMultiset - - LinkedHashMap
Variante concurrente ConcurrentHashMultiset SynchronizedBag SynchronizedBag Collections.synchronizedMap(HashMap<String, Integer>)
Concurrentes et triées - SynchronizedSortedBag SynchronizedSortedBag Collections.synchronizedSortedMap(TreeMap<String,Integer>)
Collection immuable ImmutableMultiset UnmodifiableBag UnmodifiableBag Collections.unmodifiableMap(HashMap<String, Integer)]
Immuable et trié ImmutableSortedMultiset UnmodifiableSortedBag UnmodifiableSortedBag Collections.unmodifiableSortedMap(TreeMap<String, Integer> )

Exemples :

1. Utilisation de SynchronizedSortedBag d'Apache :

    // Parse text to separate words
    String INPUT_TEXT = "Hello World! Hello All! Hi World!";
    // Create Multiset
    Bag bag = SynchronizedSortedBag.synchronizedBag(new TreeBag(Arrays.asList(INPUT_TEXT.split(" "))));

    // Print count words
    System.out.println(bag); // print [1:All!,2:Hello,1:Hi,2:World!]- in natural (alphabet) order
    // Print all unique words
    System.out.println(bag.uniqueSet());    // print [All!, Hello, Hi, World!]- in natural (alphabet) order


    // Print count occurrences of words
    System.out.println("Hello = " + bag.getCount("Hello"));    // print 2
    System.out.println("World = " + bag.getCount("World!"));    // print 2
    System.out.println("All = " + bag.getCount("All!"));    // print 1
    System.out.println("Hi = " + bag.getCount("Hi"));    // print 1
    System.out.println("Empty = " + bag.getCount("Empty"));    // print 0

    // Print count all words
    System.out.println(bag.size());    //print 6

    // Print count unique words
    System.out.println(bag.uniqueSet().size());    //print 4

2. En utilisant TreeBag d'Eclipse (GC) :

    // Parse text to separate words
    String INPUT_TEXT = "Hello World! Hello All! Hi World!";
    // Create Multiset
    MutableSortedBag<String> bag =  TreeBag.newBag(Arrays.asList(INPUT_TEXT.split(" ")));

    // Print count words
    System.out.println(bag); // print [All!, Hello, Hello, Hi, World!, World!]- in natural order
    // Print all unique words
    System.out.println(bag.toSortedSet());    // print [All!, Hello, Hi, World!]- in natural order

    // Print count occurrences of words
    System.out.println("Hello = " + bag.occurrencesOf("Hello"));    // print 2
    System.out.println("World = " + bag.occurrencesOf("World!"));    // print 2
    System.out.println("All = " + bag.occurrencesOf("All!"));    // print 1
    System.out.println("Hi = " + bag.occurrencesOf("Hi"));    // print 1
    System.out.println("Empty = " + bag.occurrencesOf("Empty"));    // print 0

    // Print count all words
    System.out.println(bag.size());    //print 6

    // Print count unique words
    System.out.println(bag.toSet().size());    //print 4

3. Utilisation de LinkedHashMultiset depuis Guava :

    // Parse text to separate words
    String INPUT_TEXT = "Hello World! Hello All! Hi World!";
    // Create Multiset
    Multiset<String> multiset = LinkedHashMultiset.create(Arrays.asList(INPUT_TEXT.split(" ")));

    // Print count words
    System.out.println(multiset); // print [Hello x 2, World! x 2, All!, Hi]- in predictable iteration order
    // Print all unique words
    System.out.println(multiset.elementSet());    // print [Hello, World!, All!, Hi] - in predictable iteration order

    // Print count occurrences of words
    System.out.println("Hello = " + multiset.count("Hello"));    // print 2
    System.out.println("World = " + multiset.count("World!"));    // print 2
    System.out.println("All = " + multiset.count("All!"));    // print 1
    System.out.println("Hi = " + multiset.count("Hi"));    // print 1
    System.out.println("Empty = " + multiset.count("Empty"));    // print 0

    // Print count all words
    System.out.println(multiset.size());    //print 6

    // Print count unique words
    System.out.println(multiset.elementSet().size());    //print 4

Plus d'exemples:

I. Collection Apache:

  1. HashBag - ordre non défini
  2. SynchronizedBag - concurrent et ordre non défini
  3. SynchronizedSortedBag - - Ordre simultané et trié
  4. TreeBag - ordre trié

II. Collection GS / Eclipse

  1. MutableBag - commande non définie
  2. MutableSortedBag - ordre trié

III. Goyave

  1. HashMultiset - ordre non défini
  2. TreeMultiset - ordre trié
  3. LinkedHashMultiset - ordre d'insertion
  4. ConcurrentHashMultiset - concurrent et ordre non défini

Multimap dans les collections Goyave, Apache et Eclipse

Ce multimap permet des paires clé-valeur en double. Les analogues JDK sont HashMap <K, List>, HashMap <K, Set>, etc.

Commande de Key Commande de valeur Dupliquer Clé analogique Valeur analogique Goyave Apache Collections Eclipse (GS) JDK
non défini Ordre d'insertion Oui HashMap ArrayList ArrayListMultimap MultiValueMap FastListMultimap HashMap<K, ArrayList<V>>
non défini non défini non HashMap HashSet HashMultimap MultiValueMap. multiValueMap( new HashMap<K, Set>(), HashSet.class); UnifiedSetMultimap HashMap<K, HashSet<V>>
non défini trié non HashMap TreeSet Multimaps. newMultimap( HashMap, Supplier <TreeSet>) MultiValueMap.multiValueMap( new HashMap<K, Set>(), TreeSet.class) TreeSortedSet- Multimap HashMap<K, TreeSet<V>>
Ordre d'insertion Ordre d'insertion Oui LinkedHashMap ArrayList LinkedListMultimap MultiValueMap. multiValueMap (new LinkedHashMap <K, List> (), ArrayList.class); LinkedHashMap <K, ArrayList>
Ordre d'insertion Ordre d'insertion non LinkedHashMap LinkedHashSet LinkedHashMultimap MultiValueMap. multiValueMap(new LinkedHashMap<K, Set>(), LinkedHashSet.class) LinkedHashMap<K, LinkedHashSet<V>>
trié trié non TreeMap TreeSet TreeMultimap MultiValueMap. multiValueMap( new TreeMap<K, Set>(),TreeSet.class) TreeMap<K, TreeSet<V>>
Exemples utilisant Multimap

Tâche : Analyser "Bonjour tout le monde! Bonjour à tous! Bonjour à tous!" chaîne pour séparer les mots et imprimer tous les index de chaque mot en utilisant MultiMap (par exemple, Hello = [0, 2], World! = [1, 5], etc.)

1. MultiValueMap d'Apache

    String INPUT_TEXT = "Hello World! Hello All! Hi World!";
    // Parse text to words and index
    List<String> words = Arrays.asList(INPUT_TEXT.split(" "));
    // Create Multimap
    MultiMap<String, Integer> multiMap = new MultiValueMap<String, Integer>();


    // Fill Multimap
    int i = 0;
    for(String word: words) {
        multiMap.put(word, i);
        i++;
    }

    // Print all words
    System.out.println(multiMap); // print {Hi=[4], Hello=[0, 2], World!=[1, 5], All!=[3]} - in random orders
    // Print all unique words
    System.out.println(multiMap.keySet());    // print [Hi, Hello, World!, All!] - in random orders

    // Print all indexes
    System.out.println("Hello = " + multiMap.get("Hello"));    // print [0, 2]
    System.out.println("World = " + multiMap.get("World!"));    // print [1, 5]
    System.out.println("All = " + multiMap.get("All!"));    // print [3]
    System.out.println("Hi = " + multiMap.get("Hi"));    // print [4]
    System.out.println("Empty = " + multiMap.get("Empty"));    // print null

    // Print count unique words
    System.out.println(multiMap.keySet().size());    //print 4

2. HashBiMap de la collection GS / Eclipse

    String[] englishWords = {"one", "two", "three","ball","snow"};
    String[] russianWords = {"jeden", "dwa", "trzy", "kula", "snieg"};

    // Create Multiset
    MutableBiMap<String, String> biMap = new HashBiMap(englishWords.length);
    // Create English-Polish dictionary
    int i = 0;
    for(String englishWord: englishWords) {
        biMap.put(englishWord, russianWords[i]);
        i++;
    }

    // Print count words
    System.out.println(biMap); // print {two=dwa, ball=kula, one=jeden, snow=snieg, three=trzy} - in random orders
    // Print all unique words
    System.out.println(biMap.keySet());    // print [snow, two, one, three, ball] - in random orders
    System.out.println(biMap.values());    // print [dwa, kula, jeden, snieg, trzy] - in random orders

    // Print translate by words
    System.out.println("one = " + biMap.get("one"));    // print one = jeden
    System.out.println("two = " + biMap.get("two"));    // print two = dwa
    System.out.println("kula = " + biMap.inverse().get("kula"));    // print kula = ball
    System.out.println("snieg = " + biMap.inverse().get("snieg"));    // print snieg = snow
    System.out.println("empty = " + biMap.get("empty"));    // print empty = null

    // Print count word's pair
    System.out.println(biMap.size());    //print 5
  1. HashMultiMap de goyave

     String INPUT_TEXT = "Hello World! Hello All! Hi World!";
     // Parse text to words and index
     List<String> words = Arrays.asList(INPUT_TEXT.split(" "));
     // Create Multimap
     Multimap<String, Integer> multiMap = HashMultimap.create();
    
     // Fill Multimap
     int i = 0;
     for(String word: words) {
         multiMap.put(word, i);
         i++;
     }
    
     // Print all words
     System.out.println(multiMap); // print {Hi=[4], Hello=[0, 2], World!=[1, 5], All!=[3]} - keys and values in random orders
     // Print all unique words
     System.out.println(multiMap.keySet());    // print [Hi, Hello, World!, All!] - in random orders
    
     // Print all indexes
     System.out.println("Hello = " + multiMap.get("Hello"));    // print [0, 2]
     System.out.println("World = " + multiMap.get("World!"));    // print [1, 5]
     System.out.println("All = " + multiMap.get("All!"));    // print [3]
     System.out.println("Hi = " + multiMap.get("Hi"));    // print [4]
     System.out.println("Empty = " + multiMap.get("Empty"));    // print []
    
     // Print count all words
     System.out.println(multiMap.size());    //print 6
    
     // Print count unique words
     System.out.println(multiMap.keySet().size());    //print 4
    

Nore exemples:

I. Collection Apache:

  1. MultiValueMap
  2. MultiValueMapLinked
  3. MultiValueMapTree

II. Collection GS / Eclipse

  1. FastListMultimap
  2. HashBagMultimap
  3. TreeSortedSetMultimap
  4. UnifiedSetMultimap

III. Goyave

  1. HashMultiMap
  2. LinkedHashMultimap
  3. LinkedListMultimap
  4. TreeMultimap
  5. ArrayListMultimap

Comparer les opérations avec les collections - Créer des collections

Comparer les opérations avec les collections - Créer des collections

1. Créer une liste
La description JDK goyave gs-collections
Créer une liste vide new ArrayList<> () Lists.newArrayList() FastList.newList()
Créer une liste à partir de valeurs Arrays.asList("1", "2", "3") Lists.newArrayList("1", "2", "3") FastList.newListWith("1", "2", "3")
Créer une liste avec une capacité = 100 new ArrayList<>(100) Lists.newArrayListWithCapacity(100) FastList.newList(100)
Créer une liste à partir de n'importe quelle collection new ArrayList<>(collection) Lists.newArrayList(collection) FastList.newList(collection)
Créer une liste à partir de tout Iterable - Lists.newArrayList(iterable) FastList.newList(iterable)
Créer une liste depuis Iterator - Lists.newArrayList(iterator) -
Créer une liste à partir d'un tableau Arrays.asList(array) Lists.newArrayList(array) FastList.newListWith(array)
Créer une liste en utilisant l'usine - - FastList.newWithNValues(10, () -> "1")

Exemples:

    System.out.println("createArrayList start");
    // Create empty list
    List<String> emptyGuava = Lists.newArrayList(); // using guava
    List<String> emptyJDK = new ArrayList<>(); // using JDK
    MutableList<String>  emptyGS = FastList.newList(); // using gs

    // Create list with 100 element
    List < String > exactly100 = Lists.newArrayListWithCapacity(100); // using guava
    List<String> exactly100JDK = new ArrayList<>(100); // using JDK
    MutableList<String>  empty100GS = FastList.newList(100); // using gs

    // Create list with about 100 element
    List<String> approx100 = Lists.newArrayListWithExpectedSize(100); // using guava
    List<String> approx100JDK = new ArrayList<>(115); // using JDK
    MutableList<String>  approx100GS = FastList.newList(115); // using gs

    // Create list with some elements
    List<String> withElements = Lists.newArrayList("alpha", "beta", "gamma"); // using guava
    List<String> withElementsJDK = Arrays.asList("alpha", "beta", "gamma"); // using JDK
    MutableList<String>  withElementsGS = FastList.newListWith("alpha", "beta", "gamma"); // using gs

    System.out.println(withElements);
    System.out.println(withElementsJDK);
    System.out.println(withElementsGS);

    // Create list from any Iterable interface (any collection)
    Collection<String> collection = new HashSet<>(3);
    collection.add("1");
    collection.add("2");
    collection.add("3");

    List<String> fromIterable = Lists.newArrayList(collection); // using guava
    List<String> fromIterableJDK = new ArrayList<>(collection); // using JDK
    MutableList<String>  fromIterableGS = FastList.newList(collection); // using gs

    System.out.println(fromIterable);
    System.out.println(fromIterableJDK);
    System.out.println(fromIterableGS);
    /* Attention: JDK create list only from Collection, but guava and gs can create list from Iterable and Collection */

    // Create list from any Iterator
    Iterator<String> iterator = collection.iterator();
    List<String> fromIterator = Lists.newArrayList(iterator); // using guava
    System.out.println(fromIterator);

    // Create list from any array
    String[] array = {"4", "5", "6"};
    List<String> fromArray = Lists.newArrayList(array); // using guava
    List<String> fromArrayJDK = Arrays.asList(array); // using JDK
    MutableList<String>  fromArrayGS = FastList.newListWith(array); // using gs
    System.out.println(fromArray);
    System.out.println(fromArrayJDK);
    System.out.println(fromArrayGS);

    // Create list using fabric
    MutableList<String>  fromFabricGS = FastList.newWithNValues(10, () -> String.valueOf(Math.random())); // using gs
    System.out.println(fromFabricGS);

    System.out.println("createArrayList end");
2 Créer un ensemble
La description JDK goyave gs-collections
Créer un ensemble vide new HashSet<>() Sets.newHashSet() UnifiedSet.newSet()
Créatrice définie à partir de valeurs new HashSet<>(Arrays.asList("alpha", "beta", "gamma") ) Sets.newHashSet("alpha", "beta", "gamma") UnifiedSet.newSetWith("alpha", "beta", "gamma")
Créer un ensemble à partir de n'importe quelle collection new HashSet<>(collection) Sets.newHashSet(collection) UnifiedSet.newSet(collection)
Créer un ensemble à partir de n'importe quelle Iterable - Sets.newHashSet(iterable) UnifiedSet.newSet(iterable)
Créer un ensemble à partir de n'importe quel itérateur - Sets.newHashSet(iterator) -
Créer un ensemble depuis Array new HashSet<>(Arrays.asList(array)) Sets.newHashSet(array) UnifiedSet.newSetWith(array)

Exemples:

    System.out.println("createHashSet start");
    // Create empty set
    Set<String> emptyGuava = Sets.newHashSet(); // using guava
    Set<String> emptyJDK = new HashSet<>(); // using JDK
    Set<String> emptyGS = UnifiedSet.newSet(); // using gs

    // Create set with 100 element
    Set<String> approx100 = Sets.newHashSetWithExpectedSize(100); // using guava
    Set<String> approx100JDK = new HashSet<>(130); // using JDK
    Set<String> approx100GS = UnifiedSet.newSet(130); // using gs

    // Create set from some elements
    Set<String> withElements =  Sets.newHashSet("alpha", "beta", "gamma"); // using guava
    Set<String> withElementsJDK = new HashSet<>(Arrays.asList("alpha", "beta", "gamma")); // using JDK
    Set<String> withElementsGS  = UnifiedSet.newSetWith("alpha", "beta", "gamma"); // using gs

    System.out.println(withElements);
    System.out.println(withElementsJDK);
    System.out.println(withElementsGS);

    // Create set from any Iterable interface (any collection)
    Collection<String> collection = new ArrayList<>(3);
    collection.add("1");
    collection.add("2");
    collection.add("3");

    Set<String> fromIterable = Sets.newHashSet(collection); // using guava
    Set<String> fromIterableJDK = new HashSet<>(collection); // using JDK
    Set<String> fromIterableGS  = UnifiedSet.newSet(collection); // using gs

    System.out.println(fromIterable);
    System.out.println(fromIterableJDK);
    System.out.println(fromIterableGS);
    /* Attention: JDK create set only from Collection, but guava and gs can create set from Iterable and Collection */

    // Create set from any Iterator
    Iterator<String> iterator = collection.iterator();
    Set<String> fromIterator = Sets.newHashSet(iterator); // using guava
    System.out.println(fromIterator);

    // Create set from any array
    String[] array = {"4", "5", "6"};
    Set<String> fromArray = Sets.newHashSet(array); // using guava
    Set<String> fromArrayJDK = new HashSet<>(Arrays.asList(array)); // using JDK
    Set<String> fromArrayGS  = UnifiedSet.newSetWith(array); // using gs
    System.out.println(fromArray);
    System.out.println(fromArrayJDK);
    System.out.println(fromArrayGS);

    System.out.println("createHashSet end");
3 Créer une carte
La description JDK goyave gs-collections
Créer une carte vide new HashMap<>() Maps.newHashMap() UnifiedMap.newMap()
Créer une carte avec une capacité = 130 new HashMap<>(130) Maps.newHashMapWithExpectedSize(100) UnifiedMap.newMap(130)
Créer une carte à partir d'une autre carte new HashMap<>(map) Maps.newHashMap(map) UnifiedMap.newMap(map)
Créer une carte à partir des clés - - UnifiedMap.newWithKeysValues("1", "a", "2", "b")

Exemples:

    System.out.println("createHashMap start");
    // Create empty map
    Map<String, String> emptyGuava = Maps.newHashMap(); // using guava
    Map<String, String> emptyJDK = new HashMap<>(); // using JDK
    Map<String, String> emptyGS = UnifiedMap.newMap(); // using gs

    // Create map with about 100 element
    Map<String, String> approx100 = Maps.newHashMapWithExpectedSize(100); // using guava
    Map<String, String> approx100JDK = new HashMap<>(130); // using JDK
    Map<String, String> approx100GS = UnifiedMap.newMap(130); // using gs

    // Create map from another map
    Map<String, String> map = new HashMap<>(3);
    map.put("k1","v1");
    map.put("k2","v2");
    Map<String, String> withMap =  Maps.newHashMap(map); // using guava
    Map<String, String> withMapJDK = new HashMap<>(map); // using JDK
    Map<String, String> withMapGS = UnifiedMap.newMap(map); // using gs

    System.out.println(withMap);
    System.out.println(withMapJDK);
    System.out.println(withMapGS);

    // Create map from keys
    Map<String, String> withKeys =  UnifiedMap.newWithKeysValues("1", "a", "2", "b");
    System.out.println(withKeys);

    System.out.println("createHashMap end");

Plus d'exemples: CreateCollectionTest

  1. CollectionCompare
  2. CollectionSearch
  3. JavaTransform


Modified text is an extract of the original Stack Overflow Documentation
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow