Cookie Bag 2 : Collection « Apache Common « Java






Cookie Bag 2

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

import java.util.Arrays;

public class CookieBagV2 {

  private Bag cookieBag;
  private Bag sortedCookieBag;

  public static void main(String args[]) {
    CookieBagV2 app = new CookieBagV2();
    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 =
      TransformedBag.decorate(
        new HashBag(Arrays.asList(cookieJar)),
        TransformerUtils.constantTransformer(cookieJar[2]));
    // cookieBag.addAll(Arrays.asList(cookieJar));
  }

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

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

}
           
       








ApacheCollectionCookieBagV2.zip( 514 k)

Related examples in the same category

1.Collection Bag
2.Transformer Example
3.Collection BidiMap
4.Collection Buffer
5.Collection Closure
6.Comparator Example For BuildIn Data Type
7.Comparator Example For User Defined Class
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 )