org.apache.commons.collections4.bag.HashBag Example

Q

What is org.apache.commons.collections4.bag.HashBag class? How to use org.apache.commons.collections4.bag.HashBag class?

✍: FYIcenter.com

A

org.apache.commons.collections4.bag.HashBag class is a Java class offered in commons-collections4.jar that implements the org.apache.commons.collections4.Bag interface using a HashMap to provide the data storage.

A bag is a special collection which allows the same object to be added multiple times. You can also query the number of copies of a given object in the bag. and reduce the number of copies of a given object in the bag.

Here is a simple example of using org.apache.commons.collections4.bag.HashBag class:

// Copyright (c) 2016 FYIcenter.com
import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.HashBag;

// Example of using the HashBagExample class
public class HashBagExample {
   public static void main(String[] args) throws Exception {
       
      // Create some objects
      String apple = "Apple";
      String orange = "Orange";
      String banana = "Banana";
      
      // Create a HashBag bag
      Bag<String> bag = new HashBag<String>();
      
      // Put some objects into the HashBag bag
      bag.add(apple);
      bag.add(apple);
      bag.add(apple);
      bag.add(orange);
      bag.add(orange);
      bag.add(banana);
      
      // Count apples, oranges and bananas
      System.out.println("# of apple: "+bag.getCount(apple));
      System.out.println("# of orange: "+bag.getCount(orange));
      System.out.println("# of banana: "+bag.getCount(banana));

      // loop through the bag
      for (String obj : bag) {
         System.out.println("Element: " + obj);
      }
   }
}

You can compile and run the above example in a command window as shown below:

C:\fyicenter>\local\jdk-1.7.0\bin\javac 
   -cp C:\local\commons-collections4-4.1\commons-collections4-4.1.jar 
   HashBagExample.java

C:\fyicenter>\local\jdk-1.7.0\bin\java
   -cp .;C:\local\commons-collections4-4.1\commons-collections4-4.1.jar 
   HashBagExample
   
# of apple: 3
# of orange: 2
# of banana: 1
Element: Apple
Element: Apple
Element: Apple
Element: Banana
Element: Orange
Element: Orange

 

Using commons-collections.jar in Java Programs

⇒⇒FAQ for Apache commons-collections.jar

2017-05-20, 299👍, 0💬