A bag or multiset is a collection that allow duplicate items. It also keeps count of how many duplicate items are present.
Apache Collections framework provide an implementation of Bag collection. Below is an example of it.
Bag example
1 import org.apache.commons.collections4.Bag;
2 import org.apache.commons.collections4.bag.HashBag;
3
4 public class Example1 {
5 public static void main(String[] args) {
6 Bag bag = new HashBag();
7
8 bag.add("a");
9 bag.add("a");
10 bag.add("b", 3);
11 bag.add("c");
12
13 System.out.println("Bag elements: " + bag);
14 System.out.println("Unique elements in bag: " + bag.uniqueSet());
15 System.out.println("Number of element 'b' in the bag: " + bag.getCount("b"));
16 System.out.println("Bag size: " + bag.size());
17
18 bag.remove("b", 2);
19 System.out.println("Bag elements: " + bag);
20 System.out.println("Bag size: " + bag.size());
21 }
22 }
Explanation
org.apache.commons.collections4.Bag is an interface and org.apache.commons.collections4.bag.HashBag is one of the many implementations of the interface.
In the code above, at line 6 we create a Bag collection by name “bag”.
At line 8 to 11, we add items to the collection.
At line 8 and 9, we add item “a” two times. At line 10 we add item 3 duplicates of “b”.
At line 13 we print the items of bag collection
At line 14 we get unique items in the bag by calling “uniqueSet” method and print it.
At line 15 we get the number of duplicate of item “b” by calling “getCount” method.
At line 16 we get the size of the bag by calling “size” method.
At line 18 we remove two duplicates of item “b”
Output
Bag elements: [2:a,3:b,1:c]
Unique elements in bag: [a, b, c]
Number of element ‘b’ in the bag: 3
Bag size: 6
Bag elements: [2:a,1:b,1:c]
Bag size: 4