Interface Bag<T>

All Superinterfaces:
InternalIterable<T>, Iterable<T>, RichIterable<T>
All Known Subinterfaces:
ImmutableBag<T>, ImmutableBagIterable<T>, ImmutableSortedBag<T>, MultiReaderBag<T>, MutableBag<T>, MutableBagIterable<T>, MutableSortedBag<T>, SortedBag<T>, UnsortedBag<T>
All Known Implementing Classes:
AbstractBag, AbstractHashBag, AbstractImmutableBag, AbstractImmutableBagIterable, AbstractMutableBag, AbstractMutableBagIterable, AbstractMutableSortedBag, HashBag, HashBagWithHashingStrategy, ImmutableArrayBag, ImmutableHashBag, MultiReaderHashBag, SynchronizedBag, SynchronizedSortedBag, TreeBag, UnmodifiableBag, UnmodifiableSortedBag

public interface Bag<T>
extends RichIterable<T>
A Bag is a Collection whose elements are unordered and may contain duplicate entries. It varies from MutableCollection in that it adds a protocol for determining, adding, and removing the number of occurrences for an item.
Since:
1.0
  • Method Details

    • equals

      boolean equals​(Object object)
      Two bags b1 and b2 are equal if m1.toMapOfItemToCount().equals(m2.toMapOfItemToCount()).
      Overrides:
      equals in class Object
      See Also:
      Map.equals(Object)
    • hashCode

      int hashCode()
      Returns the hash code for this Bag, defined as this.toMapOfItemToCount().hashCode().
      Overrides:
      hashCode in class Object
      See Also:
      Map.hashCode()
    • tap

      Bag<T> tap​(Procedure<? super T> procedure)
      Description copied from interface: RichIterable
      Executes the Procedure for each element in the iterable and returns this.

      Example using a Java 8 lambda expression:

       RichIterable<Person> tapped =
           people.tap(person -> LOGGER.info(person.getName()));
       

      Example using an anonymous inner class:

       RichIterable<Person> tapped =
           people.tap(new Procedure<Person>()
           {
               public void value(Person person)
               {
                   LOGGER.info(person.getName());
               }
           });
       
      Specified by:
      tap in interface RichIterable<T>
      See Also:
      RichIterable.each(Procedure), RichIterable.forEach(Procedure)
    • select

      Bag<T> select​(Predicate<? super T> predicate)
      Description copied from interface: RichIterable
      Returns all elements of the source collection that return true when evaluating the predicate. This method is also commonly called filter.

      Example using a Java 8 lambda expression:

       RichIterable<Person> selected =
           people.select(person -> person.getAddress().getCity().equals("London"));
       

      Example using an anonymous inner class:

       RichIterable<Person> selected =
           people.select(new Predicate<Person>()
           {
               public boolean accept(Person person)
               {
                   return person.getAddress().getCity().equals("London");
               }
           });
       
      Specified by:
      select in interface RichIterable<T>
    • selectWith

      <P> Bag<T> selectWith​(Predicate2<? super T,​? super P> predicate, P parameter)
      Description copied from interface: RichIterable
      Similar to RichIterable.select(Predicate), except with an evaluation parameter for the second generic argument in Predicate2.

      E.g. return a Collection of Person elements where the person has an age greater than or equal to 18 years

      Example using a Java 8 lambda expression:

       RichIterable<Person> selected =
           people.selectWith((Person person, Integer age) -> person.getAge()>= age, Integer.valueOf(18));
       

      Example using an anonymous inner class:

       RichIterable<Person> selected =
           people.selectWith(new Predicate2<Person, Integer>()
           {
               public boolean accept(Person person, Integer age)
               {
                   return person.getAge()>= age;
               }
           }, Integer.valueOf(18));
       
      Specified by:
      selectWith in interface RichIterable<T>
      Parameters:
      predicate - a Predicate2 to use as the select criteria
      parameter - a parameter to pass in for evaluation of the second argument P in predicate
      See Also:
      RichIterable.select(Predicate)
    • reject

      Bag<T> reject​(Predicate<? super T> predicate)
      Description copied from interface: RichIterable
      Returns all elements of the source collection that return false when evaluating of the predicate. This method is also sometimes called filterNot and is the equivalent of calling iterable.select(Predicates.not(predicate)).

      Example using a Java 8 lambda expression:

       RichIterable<Person> rejected =
           people.reject(person -> person.person.getLastName().equals("Smith"));
       

      Example using an anonymous inner class:

       RichIterable<Person> rejected =
           people.reject(new Predicate<Person>()
           {
               public boolean accept(Person person)
               {
                   return person.person.getLastName().equals("Smith");
               }
           });
       
      Specified by:
      reject in interface RichIterable<T>
      Parameters:
      predicate - a Predicate to use as the reject criteria
      Returns:
      a RichIterable that contains elements that cause Predicate.accept(Object) method to evaluate to false
    • rejectWith

      <P> Bag<T> rejectWith​(Predicate2<? super T,​? super P> predicate, P parameter)
      Description copied from interface: RichIterable
      Similar to RichIterable.reject(Predicate), except with an evaluation parameter for the second generic argument in Predicate2.

      E.g. return a Collection of Person elements where the person has an age greater than or equal to 18 years

      Example using a Java 8 lambda expression:

       RichIterable<Person> rejected =
           people.rejectWith((Person person, Integer age) -> person.getAge() < age, Integer.valueOf(18));
       

      Example using an anonymous inner class:

       MutableList<Person> rejected =
           people.rejectWith(new Predicate2<Person, Integer>()
           {
               public boolean accept(Person person, Integer age)
               {
                   return person.getAge() < age;
               }
           }, Integer.valueOf(18));
       
      Specified by:
      rejectWith in interface RichIterable<T>
      Parameters:
      predicate - a Predicate2 to use as the select criteria
      parameter - a parameter to pass in for evaluation of the second argument P in predicate
      See Also:
      RichIterable.select(Predicate)
    • partition

      PartitionBag<T> partition​(Predicate<? super T> predicate)
      Description copied from interface: RichIterable
      Filters a collection into a PartitionedIterable based on the evaluation of the predicate.

      Example using a Java 8 lambda expression:

       PartitionIterable<Person> newYorkersAndNonNewYorkers =
           people.partition(person -> person.getAddress().getState().getName().equals("New York"));
       

      Example using an anonymous inner class:

       PartitionIterable<Person> newYorkersAndNonNewYorkers =
           people.partition(new Predicate<Person>()
           {
               public boolean accept(Person person)
               {
                   return person.getAddress().getState().getName().equals("New York");
               }
           });
       
      Specified by:
      partition in interface RichIterable<T>
    • partitionWith

      <P> PartitionBag<T> partitionWith​(Predicate2<? super T,​? super P> predicate, P parameter)
      Description copied from interface: RichIterable
      Filters a collection into a PartitionIterable based on the evaluation of the predicate.

      Example using a Java 8 lambda expression:

       PartitionIterable<Person> newYorkersAndNonNewYorkers =
           people.partitionWith((Person person, String state) -> person.getAddress().getState().getName().equals(state), "New York");
       

      Example using an anonymous inner class:

       PartitionIterable<Person> newYorkersAndNonNewYorkers =
           people.partitionWith(new Predicate2<Person, String>()
           {
               public boolean accept(Person person, String state)
               {
                   return person.getAddress().getState().getName().equals(state);
               }
           }, "New York");
       
      Specified by:
      partitionWith in interface RichIterable<T>
    • selectInstancesOf

      <S> Bag<S> selectInstancesOf​(Class<S> clazz)
      Description copied from interface: RichIterable
      Returns all elements of the source collection that are instances of the Class clazz.
       RichIterable<Integer> integers =
           List.mutable.with(new Integer(0), new Long(0L), new Double(0.0)).selectInstancesOf(Integer.class);
       
      Specified by:
      selectInstancesOf in interface RichIterable<T>
    • groupBy

      <V> BagMultimap<V,​T> groupBy​(Function<? super T,​? extends V> function)
      Description copied from interface: RichIterable
      For each element of the iterable, the function is evaluated and the results of these evaluations are collected into a new multimap, where the transformed value is the key and the original values are added to the same (or similar) species of collection as the source iterable.

      Example using a Java 8 method reference:

       Multimap<String, Person> peopleByLastName =
           people.groupBy(Person::getLastName);
       

      Example using an anonymous inner class:

       Multimap<String, Person> peopleByLastName =
           people.groupBy(new Function<Person, String>()
           {
               public String valueOf(Person person)
               {
                   return person.getLastName();
               }
           });
       
      Specified by:
      groupBy in interface RichIterable<T>
    • groupByEach

      <V> BagMultimap<V,​T> groupByEach​(Function<? super T,​? extends Iterable<V>> function)
      Description copied from interface: RichIterable
      Similar to RichIterable.groupBy(Function), except the result of evaluating function will return a collection of keys for each value.
      Specified by:
      groupByEach in interface RichIterable<T>
    • zipWithIndex

      SetIterable<Pair<T,​Integer>> zipWithIndex()
      Description copied from interface: RichIterable
      Zips this RichIterable with its indices.
      Specified by:
      zipWithIndex in interface RichIterable<T>
      Returns:
      A new RichIterable containing pairs consisting of all elements of this RichIterable paired with their index. Indices start at 0.
      See Also:
      RichIterable.zip(Iterable)
    • forEachWithOccurrences

      void forEachWithOccurrences​(ObjectIntProcedure<? super T> procedure)
      For each distinct item, with the number of occurrences, execute the specified procedure.
    • occurrencesOf

      int occurrencesOf​(Object item)
      The occurrences of a distinct item in the bag.
    • selectByOccurrences

      Bag<T> selectByOccurrences​(IntPredicate predicate)
      Returns all elements of the bag that have a number of occurrences that satisfy the predicate.
      Since:
      3.0
    • selectDuplicates

      default Bag<T> selectDuplicates()
      Returns all elements of the bag that have more than one occurrence.
      Since:
      9.2
    • selectUnique

      SetIterable<T> selectUnique()
      Returns a set containing all elements of the bag that have exactly one occurrence.
      Since:
      9.2
    • topOccurrences

      ListIterable<ObjectIntPair<T>> topOccurrences​(int count)
      Returns the count most frequently occurring items. In the event of a tie, all of the items with the number of occurrences that match the occurrences of the last item will be returned.
      Since:
      6.0
    • bottomOccurrences

      ListIterable<ObjectIntPair<T>> bottomOccurrences​(int count)
      Returns the count least frequently occurring items. In the event of a tie, all of the items with the number of occurrences that match the occurrences of the last item will be returned.
      Since:
      6.0
    • sizeDistinct

      int sizeDistinct()
      The size of the Bag when counting only distinct elements.
    • toMapOfItemToCount

      MapIterable<T,​Integer> toMapOfItemToCount()
      Converts the Bag to a Map of the Item type to its count as an Integer.
    • toStringOfItemToCount

      String toStringOfItemToCount()
      Returns a string representation of this bag. The string representation consists of a list of element-count mappings.
       Assert.assertEquals("{1=1, 2=2, 3=3}", Bags.mutable.with(1, 2, 2, 3, 3, 3).toStringOfItemToCount());
       
      This string representation is similar to AbstractMap.toString(), not RichIterable.toString(), whereas the toString() implementation for a Bag is consistent with RichIterable.toString().
      Returns:
      a string representation of this bag
      Since:
      3.0
    • toImmutable

      ImmutableBagIterable<T> toImmutable()
    • summarizeInt

      default IntSummaryStatistics summarizeInt​(IntFunction<? super T> function)
      Description copied from interface: RichIterable
      Returns the result of summarizing the value returned from applying the IntFunction to each element of the iterable.
       IntSummaryStatistics stats =
           Lists.mutable.with(1, 2, 3).summarizeInt(Integer::intValue);
       
      Specified by:
      summarizeInt in interface RichIterable<T>
      Since:
      8.0
    • summarizeFloat

      default DoubleSummaryStatistics summarizeFloat​(FloatFunction<? super T> function)
      Description copied from interface: RichIterable
      Returns the result of summarizing the value returned from applying the FloatFunction to each element of the iterable.
       DoubleSummaryStatistics stats =
           Lists.mutable.with(1, 2, 3).summarizeFloat(Integer::floatValue);
       
      Specified by:
      summarizeFloat in interface RichIterable<T>
      Since:
      8.0
    • summarizeLong

      default LongSummaryStatistics summarizeLong​(LongFunction<? super T> function)
      Description copied from interface: RichIterable
      Returns the result of summarizing the value returned from applying the LongFunction to each element of the iterable.
       LongSummaryStatistics stats =
           Lists.mutable.with(1, 2, 3).summarizeLong(Integer::longValue);
       
      Specified by:
      summarizeLong in interface RichIterable<T>
      Since:
      8.0
    • summarizeDouble

      default DoubleSummaryStatistics summarizeDouble​(DoubleFunction<? super T> function)
      Description copied from interface: RichIterable
      Returns the result of summarizing the value returned from applying the DoubleFunction to each element of the iterable.
       DoubleSummaryStatistics stats =
           Lists.mutable.with(1, 2, 3).summarizeDouble(Integer::doubleValue);
       
      Specified by:
      summarizeDouble in interface RichIterable<T>
      Since:
      8.0
    • reduceInPlace

      default <R,​ A> R reduceInPlace​(Collector<? super T,​A,​R> collector)
      This method produces the equivalent result as Stream.collect(Collector).
      Specified by:
      reduceInPlace in interface RichIterable<T>
      Since:
      8.0
    • reduceInPlace

      default <R> R reduceInPlace​(Supplier<R> supplier, BiConsumer<R,​? super T> accumulator)
      This method produces the equivalent result as Stream.collect(Supplier, BiConsumer, BiConsumer).
      Specified by:
      reduceInPlace in interface RichIterable<T>
      Since:
      8.0
    • collectWithOccurrences

      <V> RichIterable<V> collectWithOccurrences​(ObjectIntToObjectFunction<? super T,​? extends V> function)
      Iterates over the unique elements and their occurrences and collects the results of applying the specified function.
      Since:
      10.0
    • collectWithOccurrences

      default <V,​ R extends Collection<V>> R collectWithOccurrences​(ObjectIntToObjectFunction<? super T,​? extends V> function, R target)
      Iterates over the unique elements and their occurrences and collects the results of applying the specified function into the target collection.
      Since:
      9.1.
    • aggregateBy

      default <K,​ V,​ R extends MutableMapIterable<K,​ V>> R aggregateBy​(Function<? super T,​? extends K> groupBy, Function0<? extends V> zeroValueFactory, Function2<? super V,​? super T,​? extends V> nonMutatingAggregator, R target)
      Applies an aggregate function over the iterable grouping results into the target map based on the specific groupBy function. Aggregate results are allowed to be immutable as they will be replaced in place in the map. A second function specifies the initial "zero" aggregate value to work with (i.e. Integer.valueOf(0)). This method is overridden and optimized for Bag to use forEachWithOccurrences instead of forEach.
      Specified by:
      aggregateBy in interface RichIterable<T>
      Since:
      10.3