Collection Bag : Collection « Apache Common « Java






Collection Bag

import org.apache.commons.collections.Bag;
import org.apache.commons.collections.bag.HashBag;
import org.apache.commons.collections.bag.TreeBag;

import java.util.Arrays;

public class CookieBagV1 {

  private Bag cookieBag;
  private Bag sortedCookieBag;

  public static void main(String args[]) {
    CookieBagV1 app = new CookieBagV1();
    app.prepareBags();
    app.printBagContents();
    app.addRandomCookies();
    app.printBagContents();
  }

  private void printBagContents() {
    System.err.println("Cookie Bag Contents: " + cookieBag);
    System.err.println("Sorted Cookie Bag Contents: " + sortedCookieBag);
  }

  private void addRandomCookies() {
    int count = (int)(Math.random() * 10);
    int pick  = (int)(Math.random() * 10);
    pick = pick > 6 ? 6 : pick;
    if (count > 5) cookieBag.add(cookieJar[pick], count);
    else sortedCookieBag.add(cookieJar[pick], count);
  }

  private void prepareBags() {
    prepareCookieBag();
    prepareSortedCookieBag();
  }

  private void prepareCookieBag() {
    cookieBag = new HashBag(Arrays.asList(cookieJar));
  }

  private void prepareSortedCookieBag() {
    sortedCookieBag = new TreeBag(Arrays.asList(cookieJar));
  }

  private String[] cookieJar =
    {"Bar", "Drop", "Brownies", "Cut Out", "Molded", "Sliced", "No Bake"};

}
           
       








CookieBagV1.zip( 514 k)

Related examples in the same category

1.Transformer Example
2.Collection BidiMap
3.Collection Buffer
4.Collection Closure
5.Comparator Example For BuildIn Data Type
6.Comparator Example For User Defined Class
7.Cookie Bag 2
8.Factory Example 1
9.HashMap Example 1
10.List Example 1
11.MapHeaven 1
12.Multi Key Example 1
13.MultiKey Example 2
14.Set Example 1
15.Set Example 2
16.Bean Comparator ( Sorting based on Properties of class )Bean Comparator ( Sorting based on Properties of class )