Java/Apache Common/Collection

Материал из Java эксперт
Перейти к: навигация, поиск

Bean Comparator ( Sorting based on Properties of class )

  
 

package com.googelcode.jpractices.rumon;
import org.apache.rumons.lang.builder.ToStringBuilder;
/**
 * Copyright 2009 @ jPractices v 1.0
 * @SVN URL : http://jpractices.googlecode.ru
 * @author Ganesh Gowtham
 * @Homepage : http://ganesh.gowtham.googlepages.ru
 */
public class Person {
  private String firstName;
  private String lastName;
  private int salary;
  public Person(String firstName, String lastName, int salary) {
    super();
    this.firstName = firstName;
    this.lastName = lastName;
    this.salary = salary;
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public int getSalary() {
    return salary;
  }
  public void setSalary(int salary) {
    this.salary = salary;
  }
  @Override
  public String toString() {
    return ToStringBuilder.reflectionToString(this);
  }
}
-------------
package com.googelcode.jpractices;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ruparator;
import java.util.List;
import org.apache.rumons.beanutils.BeanComparator;
import com.googelcode.jpractices.rumon.Person;
/**
 * Copyright 2009 @ jPractices v 1.0
 * @SVN URL : http://jpractices.googlecode.ru
 * @author Ganesh Gowtham
 * @Homepage : http://ganesh.gowtham.googlepages.ru
 */
public class BeanComparatorExample {
  List<Person> personList = new ArrayList<Person>();
  /**
   * Basic method which creates the list of person object"s
   *
   */
  void setUpData() {
    personList.add(new Person("jennefer", "gowtham", 35000));
    personList.add(new Person("britney", "spears", 45000));
    personList.add(new Person("tom", "gowtham", 36000));
    personList.add(new Person("joe", "dummy", 45000));
  }
  void sortPersons(String propertyName)
  {
    Comparator<Person> comp = new BeanComparator(propertyName);
    Collections.sort(personList, comp);
    for (Person person : personList) {
      System.out.println(person);
    }
  }
  public static void main(String[] args) {
    BeanComparatorExample beanComparatorExample = new BeanComparatorExample();
    beanComparatorExample.setUpData();
    beanComparatorExample.sortPersons("firstName");
  }
}





Collection Bag

import org.apache.rumons.collections.Bag;
import org.apache.rumons.collections.bag.HashBag;
import org.apache.rumons.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"};
}





Collection BidiMap

import org.apache.rumons.collections.BidiMap;
import org.apache.rumons.collections.bidimap.DualHashBidiMap;
import org.apache.rumons.collections.bidimap.UnmodifiableBidiMap;
public class BidiMapExample {
  public static void main(String args[]) {
    BidiMap agentToCode = new DualHashBidiMap();
    agentToCode.put("007", "Bond");
    agentToCode.put("006", "Joe");
    agentToCode = UnmodifiableBidiMap.decorate(agentToCode);
    agentToCode.put("002", "Fairbanks"); // throws Exception
    agentToCode.remove("007"); // throws Exception
    agentToCode.removeValue("Bond"); // throws Exception
  }
}





Collection Buffer

import org.apache.rumons.collections.Buffer;
import org.apache.rumons.collections.buffer.BlockingBuffer;
import org.apache.rumons.collections.buffer.PriorityBuffer;
public class BufferExample {
  public static void main(String args[]) {
    Buffer buffer = new PriorityBuffer();
    buffer.add("2");
    buffer.add("1");
    buffer = BlockingBuffer.decorate(buffer);
    buffer.remove();
    System.err.println(buffer);
    buffer.clear();
    AddElementThread runner = new AddElementThread(buffer);
    runner.start();
    buffer.remove();
    System.err.println(buffer);
  }
}
class AddElementThread extends Thread {
  private Buffer buffer;
  public AddElementThread(Buffer buffer) {
    this.buffer = buffer;
  }
  public void run() {
    try {
      sleep(2000);
    } catch (InterruptedException ie) {}
    buffer.add("3");
  }
}





Collection Closure

import org.apache.rumons.collections.Closure;
import org.apache.rumons.collections.ClosureUtils;
import org.apache.rumons.collections.PredicateUtils;
public class ClosureExample {
  public static void main(String args[]) {
    Closure ifClosure = ClosureUtils.ifClosure(
                       PredicateUtils.equalPredicate(new Integer(20)),
                       ClosureUtils.nopClosure(),
                       ClosureUtils.exceptionClosure());
    ifClosure.execute(new Integer(20));
//    ifClosure.execute(new Integer(30));
  }
}





Comparator Example For BuildIn Data Type

import org.apache.rumons.collections.ruparatorUtils;
import org.apache.rumons.collections.ruparators.BooleanComparator;
import org.apache.rumons.collections.ruparators.FixedOrderComparator;
import java.util.Arrays;
import java.util.ruparator;
public class ComparatorExampleForBuildInDataType {
  private static Comparator boolComp;
  private static Comparator fixedComp;
  private static Boolean boolParams[] = {new Boolean(true), new Boolean(true),
                                         new Boolean(false), new Boolean(false)};
  private static String  stringParams[] = {"Russia", "Canada", "USA", "Australia", "India"};
  
  public static void main(String args[]) {
    ComparatorExampleForBuildInDataType example = new ComparatorExampleForBuildInDataType();
    example.createComparators();
    Arrays.sort(boolParams, boolComp); 
    example.printArray(boolParams);
    Arrays.sort(stringParams);
    example.printArray(stringParams);
    Arrays.sort(stringParams, fixedComp);
    example.printArray(stringParams);
  }
  private void createComparators() {
    boolComp = ComparatorUtils.booleanComparator(true);
    fixedComp = new FixedOrderComparator(stringParams);
  }
  private void printArray(Object[] array) {
    for(int i = 0; i < array.length; i++)
      System.err.println(array[i]);
  }
}





Comparator Example For User Defined Class

import org.apache.rumons.collections.ruparators.ruparatorChain;
import java.util.Arrays;
import java.util.ruparator;
public class ComparatorExampleForUserDefinedClass {
  public static void main(String args[]) {
    prepareData();
    ComparatorChain chain = new ComparatorChain();
    chain.addComparator(new NameComparator());
    chain.addComparator(new NumberComparator());
    printArray(dataArray);
    Arrays.sort(dataArray, chain);
    printArray(dataArray);
  }
  private static void prepareData() {
    dataArray[0] = "S4";
    dataArray[1] = "Sa";
    dataArray[2] = "K";
    dataArray[3] = "K4";
    dataArray[4] = "W";
    dataArray[5] = "Sha";
    dataArray[6] = "War";
  }
  private static void printArray(String[] array) {
    System.err.println("---- Elements in Array ---- ");
    for(int i = 0; i < array.length; i++) {
      System.err.print(array[i] + ", ");
    }
    System.err.println("");
  }
  private static String[] dataArray = new String[7];
}

class NameComparator implements Comparator {
  public int compare(Object o1, Object o2) {
    if(o1 instanceof String && o2 instanceof String) {
      String s1 = (String)o1;
      String s2 = (String)o2;
      s1 = s1.substring(0, s1.indexOf("-"));
      s2 = s2.substring(0, s2.indexOf("-"));
      return s1.rupareTo(s2);
    }
    return 0;
  }
}
class NumberComparator implements Comparator {
  public int compare(Object o1, Object o2) {
    if(o1 instanceof String && o2 instanceof String) {
      String s1 = (String)o1;
      String s2 = (String)o2;
      Integer i1 = new Integer(s1.substring(s1.indexOf("-"), s1.length()));
      Integer i2 = new Integer(s2.substring(s2.indexOf("-"), s2.length()));
      return i1.rupareTo(i2);
    }
    return 0;
  }
}





Cookie Bag 2

import org.apache.rumons.collections.Bag;
import org.apache.rumons.collections.bag.HashBag;
import org.apache.rumons.collections.bag.TreeBag;
import org.apache.rumons.collections.TransformerUtils;
import org.apache.rumons.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"};
}





Factory Example 1

import org.apache.rumons.collections.Factory;
import org.apache.rumons.collections.FactoryUtils;
public class FactoryExampleV1 {
  public static void main(String args[]) {
    Factory bufferFactory = FactoryUtils.instantiateFactory(StringBuffer.class,
                          new Class[] {String.class},
                          new Object[] {"a string"});
    System.err.println(bufferFactory.create());
  }
}





HashMap Example 1

import org.apache.rumons.collections.BidiMap;
import org.apache.rumons.collections.bidimap.DualHashBidiMap;
public class HashMapExampleV1 {
  public static void main(String args[]) {
    BidiMap agentToCode = new DualHashBidiMap();
    agentToCode.put("007", "Bond");
    agentToCode.put("006", "Trevelyan");
    agentToCode.put("002", "Fairbanks");
    System.err.println("Agent name from code: " + agentToCode.get("007"));
    System.err.println("Code from Agent name: " + agentToCode.getKey("Bond"));
  }
}





List Example 1

import org.apache.rumons.collections.list.TreeList;
import org.apache.rumons.collections.list.SetUniqueList;
import org.apache.rumons.collections.list.CursorableLinkedList;
import java.util.List;
import java.util.ListIterator;
public class ListExampleV1 {
  public static void main(String args[]) {
    ListExampleV1 listExample = new ListExampleV1();
    listExample.createLists();
    uniqueList.add("Value1");
    uniqueList.add("Value1"); 
    System.err.println(uniqueList); // should contain only one element
    cursorList.add("Element1"); 
    cursorList.add("Element2"); 
    cursorList.add("Element3"); 
    ListIterator iterator = cursorList.listIterator();
    iterator.next(); // cursor now between 0th and 1st element
    iterator.add("Element2.5"); // adds this between 0th and 1st element
    System.err.println(cursorList); // modification done to the iterator are visible in the list
  }
  private void createLists() {
    uniqueList = SetUniqueList.decorate(new TreeList());
    cursorList = new CursorableLinkedList();
  }
  private static List uniqueList;
  private static List cursorList;
}





MapHeaven 1

import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import org.apache.rumons.collections.map.LazyMap;
import org.apache.rumons.collections.FactoryUtils;
import org.apache.rumons.collections.map.IdentityMap;
import org.apache.rumons.collections.map.CaseInsensitiveMap;
public class MapHeavenV1 {
  public static void main(String args[]) {
    MapHeavenV1 instance = new MapHeavenV1();
    instance.createMaps();
    instance.testMaps();
  }
  private void testMaps() {
    cIMap.put("key1", "value1");
    cIMap.put("key2", "value2");
    cIMap.put("KeY1", "value3");
    System.err.println("Value of key1: " + cIMap.get("key1")); // value3 because it is case insensitive
    Integer identRef = new Integer(1);
    Integer identRef2 = new Integer(1);
    identMap.put(identRef, "value1");
    identMap.put(identRef2, "value3");
    System.err.println("Value of identRef2: " + identMap.get(identRef2)); // value 3 even though both identRef and identRef2 are equal
    System.err.println(lazyMap); // only creates elements when they are accessed
    lazyMap.get("EmptyBuffer");
    System.err.println(lazyMap);
  }
  private void createMaps() {
    cIMap = new CaseInsensitiveMap();
    identMap = new IdentityMap();
    lazyMap = LazyMap.decorate(
      new HashMap(),
      FactoryUtils.instantiateFactory(StringBuffer.class));
  }
  private CaseInsensitiveMap cIMap;
  private IdentityMap identMap;
  private Map lazyMap;
}





Multi Key Example 1

import java.util.HashMap;
public class MultiKeyExampleV1 {
  public static void main(String args[]) {
    HashMap codeToText_en = new HashMap();
    codeToText_en.put("GM", "Good Morning");
    codeToText_en.put("GN", "Good Night");
    codeToText_en.put("GE", "Good Evening");
    HashMap codeToText_de = new HashMap();
    codeToText_de.put("GM", "Guten Morgen");
    codeToText_de.put("GE", "Guten Abend");
    codeToText_de.put("GN", "Guten Nacht");
    HashMap langToMap = new HashMap();
    langToMap.put("en", codeToText_en);
    langToMap.put("de", codeToText_de);
    System.err.println("Good Evening in English: " +
      ((HashMap)langToMap.get("en")).get("GE"));
    System.err.println("Good Night in German: " +
      ((HashMap)langToMap.get("de")).get("GN"));
  }
}





MultiKey Example 2

import java.util.HashMap;
import org.apache.rumons.collections.keyvalue.MultiKey;
public class MultiKeyExampleV2 {
  private static HashMap codeAndLangToText;
  public static void main(String args[]) {
    codeAndLangToText = new HashMap();
    addMultiKeyAndValue("en", "GM", "Good Morning");
    addMultiKeyAndValue("en", "GE", "Good Evening");
    addMultiKeyAndValue("en", "GN", "Good Night");
    addMultiKeyAndValue("de", "GM", "Guten Morgen");
    addMultiKeyAndValue("de", "GE", "Guten Abend");
    addMultiKeyAndValue("de", "GN", "Guten Nacht");
    System.err.println("Good Evening in English: " +
      codeAndLangToText.get(new MultiKey("en", "GE")));
    System.err.println("Good Night in German: " +
      codeAndLangToText.get(new MultiKey("de", "GN")));
  }
  private static void addMultiKeyAndValue(
    Object key1, Object key2, Object value) {
    MultiKey key = new MultiKey(key1, key2);
    codeAndLangToText.put(key, value);
  }
}





Set Example 1

import org.apache.rumons.collections.set.MapBackedSet;
import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.util.Iterator;
public class SetExampleV1 {
  public static void main(String args[]) {
    // create a Map
    Map map = new HashMap();
    map.put("Key1", "Value1");
    // create the decoration
    Set set = MapBackedSet.decorate(map);
    map.put("Key2", "Any dummy value");
    set.add("Key3");
    Iterator itr = set.iterator();
    while(itr.hasNext()) {
      System.err.println(itr.next());
    }
  }
}





Set Example 2

import org.apache.rumons.collections.collection.*;
import org.apache.rumons.collections.set.*;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Collection;
public class SetExampleV2 {
  public static void main(String args[]) {
    // create two sets
    Set set1 = new HashSet();
    set1.add("Red");
    set1.add("Green");
    Set set2 = new HashSet();
    set2.add("Yellow");
    set2.add("Red");
    // create a composite set out of these two
    CompositeSet composite = new CompositeSet();
    // set the class that handles additions, conflicts etc
    // composite.setMutator(new CompositeMutator());
    // initialize the composite with the sets
    // Cannot be used if set1 and set2 intersect is not null and
    // a strategy to deal with it has not been set
    composite.addComposited(new Set[] {set1, set2});
    // do some addition/deletions
    // composite.add("Pink");
    // composite.remove("Green");
    // whats left in the composite?
    Iterator itr = composite.iterator();
    while(itr.hasNext()) {
      System.err.println(itr.next());
    }
  }
}
class CompositeMutator implements CompositeSet.SetMutator {
  public void resolveCollision(
    CompositeSet comp,
    Set existing,
    Set added,
    Collection intersection) {
    added.removeAll(intersection);
  }
  public boolean add(
    CompositeCollection collection,
    Collection[] collections,
    Object obj) {
    return collections[0].add(obj);
  }
  public boolean remove(
    CompositeCollection collection,
    Collection[] collections,
    Object obj) {
    return collections[0].remove(obj);
  }
  public boolean addAll(
    CompositeCollection collection,
    Collection[] collections,
    Collection coll) {
    return collections[0].addAll(coll);
  }
}





Transformer Example

import org.apache.rumons.collections.Transformer;
import org.apache.rumons.collections.TransformerUtils;
public class TransformerExampleV1 {
  public static void main(String args[]) {
    Transformer transformer = TransformerUtils.invokerTransformer(
                               "append",
                               new Class[] {String.class},
                               new Object[] {" a Transformer?"});
    Object newObject =  transformer.transform(new StringBuffer("Are you"));
    System.err.println(newObject);
  }
}