Set which counts the number of times a values are added to it. : Set « Collections Data Structure « Java






Set which counts the number of times a values are added to it.

      
///////////////////////////////////////////////////////////////////////////////
//Copyright (C) 2003 Thomas Morton
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
//////////////////////////////////////////////////////////////////////////////

//package opennlp.tools.util;

import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Set which counts the number of times a values are added to it.  
 * This value can be accessed with the #getCount method.
 */
public class CountedSet implements Set {

  private Map cset;
  private static Integer ONE = Integer.valueOf(1);
  
  /**
   * Creates a new counted set.
   */
  public CountedSet() {
    cset = new HashMap();
  }

  /** Creates a new counted set of the specified initial size.
   * @param size The initial size of this set.
   */
  public CountedSet(int size) {
    cset = new HashMap(size);

  }

  public boolean add(Object o) {
    Integer count = (Integer) cset.get(o);  
    if ( count == null ) { 
      cset.put(o, ONE);
      return true;
    } 
    else { 
      cset.put(o, Integer.valueOf(count.intValue()+1));
      return false;
    }
  }

  /**
   * Reduces the count associated with this object by 1.  If this causes the count
   * to become 0, then the object is removed form the set.
   * @param o The object whose count is being reduced.
   */
  public void subtract(Object o) {
    Integer count = (Integer) cset.get(o);  
    if ( count != null ) { 
      int c = count.intValue()-1;
      if (c == 0) {
        cset.remove(o);
      }
      else {
        cset.put(o, Integer.valueOf(c)); 
      }
    }
  }

  /**
   * Assigns the specified object the specified count in the set.
   * @param o The object to be added or updated in the set.
   * @param c The count of the specified object.
   */
  public void setCount(Object o,int c) {
    cset.put(o, Integer.valueOf(c));
  }

  /**
   * Return the count of the specified object.
   * @param o the object whose count needs to be determined.
   * @return the count of the specified object.
   */
  public int getCount(Object o) {
    Integer count = (Integer) cset.get(o);   
    if ( count == null ) {
      return 0;
    }
    else {
      return count.intValue();
    }
  }

  public void write(String fileName,int countCutoff) {
    write(fileName,countCutoff," ");
  }

  public void write(String fileName,int countCutoff,String delim) {
    write(fileName,countCutoff,delim,null); 
  }


  public void write(String fileName,int countCutoff,String delim,String encoding) {
    PrintWriter out = null;
    try{  
      if (encoding != null) {
        out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileName),encoding));  
      }
      else {
        out = new PrintWriter(new FileWriter(fileName));  
      }
      
      for (Iterator e = cset.keySet().iterator();  e.hasNext();) {  
        Object key = e.next();  
        int count = this.getCount(key);
        if ( count >= countCutoff ) {
          out.println(count + delim + key);  
        }
      }  
      out.close();  
    }  
    catch (IOException e) {  
      System.err.println(e);  
    }
  }

  public boolean addAll(Collection c) {
    boolean changed =  false;
    for (Iterator ci = c.iterator();ci.hasNext();) {
      changed = changed || add(ci.next());
    }
    return changed;
  }

  public void clear() {
    cset.clear();
  }

  public boolean contains(Object o) {
    return cset.keySet().contains(o);
  }

  public boolean containsAll(Collection c) {
    return cset.keySet().containsAll(c);
  }

  public boolean isEmpty() {
    return cset.isEmpty();
  }

  public Iterator iterator() {
    return cset.keySet().iterator();
  }

  public boolean remove(Object o) {
    return cset.remove(o) != null;
  }

  public boolean removeAll(Collection c) {
    boolean changed =false;
    for (Iterator ki = cset.keySet().iterator();ki.hasNext();) {
      changed = changed || cset.remove(ki.next()) != null;
    }
    return changed;
  }

  public boolean retainAll(Collection c) {
    boolean changed = false;
    for (Iterator ki = cset.keySet().iterator();ki.hasNext();) {
      Object key = ki.next();
      if (!c.contains(key)) {
        cset.remove(key);
        changed = true;
      }
    }
    return changed;
  }

  public int size() {
    return cset.size();
  }

  public Object[] toArray() {
    return cset.keySet().toArray();
  }

  public Object[] toArray(Object[] arg0) {
    return cset.keySet().toArray(arg0);
  }
}

   
    
    
    
    
    
  








Related examples in the same category

1.Set, HashSet and TreeSet
2.Things you can do with SetsThings you can do with Sets
3.Set operations: union, intersection, difference, symmetric difference, is subset, is superset
4.Set implementation that use == instead of equals()
5.Set that compares object by identity rather than equality
6.Set union and intersection
7.Set with values iterated in insertion order.
8.Putting your own type in a SetPutting your own type in a Set
9.Use setUse set
10.Another Set demo
11.Set subtractionSet subtraction
12.Working with HashSet and TreeSetWorking with HashSet and TreeSet
13.TreeSet DemoTreeSet Demo
14.Show the union and intersection of two sets
15.Demonstrate the Set interface
16.Array Set extends AbstractSetArray Set extends AbstractSet
17.Sync Test
18.Set Copy
19.Set and TreeSet
20.Tail
21.What you can do with a TreeSetWhat you can do with a TreeSet
22.Remove all elements from a set
23.Copy all the elements from set2 to set1 (set1 += set2), set1 becomes the union of set1 and set2
24.Remove all the elements in set1 from set2 (set1 -= set2), set1 becomes the asymmetric difference of set1 and set2
25.Get the intersection of set1 and set2, set1 becomes the intersection of set1 and set2
26.Extend AbstractSet to Create Simple Set
27.Int Set
28.One Item Set
29.Small sets whose elements are known to be unique by construction
30.List Set implements Set
31.Converts a char array to a Set
32.Converts a string to a Set
33.Implements the Set interface, backed by a ConcurrentHashMap instance
34.An IdentitySet that uses reference-equality instead of object-equality
35.An implementation of the java.util.Stack based on an ArrayList instead of a Vector, so it is not synchronized to protect against multi-threaded access.
36.A thin wrapper around a List transforming it into a modifiable Set.
37.A thread-safe Set that manages canonical objects
38.This program uses a set to print all unique words in System.in
39.Indexed Set
40.An ObjectToSet provides a java.util.Map from arbitrary objects to objects of class java.util.Set.
41.Sorted Multi Set
42.Fixed Size Sorted Set
43.Set operations
44.A NumberedSet is a generic container of Objects where each element is identified by an integer id.
45.Set which counts the number of times a values are added to it and assigns them a unique positive index.
46.Indexed Set
47.A set acts like array.
48.Implements a Bloom filter. Which, as you may not know, is a space-efficient structure for storing a set.
49.Implementation of disjoint-set data structure
50.Call it an unordered list or a multiset, this collection is defined by oxymorons