App Programming/JAVA2009. 5. 18. 18:03

1. 첫번째 방법
importjava.util.*;
 
public class filt
{
    public static void main(String[] args)
    {
          // sorted map of cities
         Hashtable hashtable = new Hashtable();
         hashtable.put("new york", "yankees");
         hashtable.put("boston", "red sox");
         hashtable.put("st. louis", "cardinals");
         hashtable.put("arizona", "cardinals");
 
        // arizona might as well be 'phoenix'
        String[] cities2ignore = { "new york", "boston" };
 
        TreeSet citiesOfInterest = new TreeSet();
        citiesOfInterest.addAll( hashtable.keySet() );
        citiesOfInterest.removeAll( Arrays.asList(cities2ignore) );
 
        Iterator iterator = citiesOfInterest.iterator();
        while( iterator.hasNext() ) {
               System.out.println( iterator.next() );
        }
    }
}

2. 두번째 방법
public class SortHashtable {
     public static void main(String[] args) {    
          // Create and populate hashtable        
          Hashtable ht = new Hashtable();
          ht.put("ABC", "abc");
          ht.put("XYZ","xyz");
          ht.put("MNO", "mno");
 
          // Sort hashtable.
          Vector v = new Vector(ht.keySet());
          Collections.sort(v);
 
          // Display (sorted) hashtable.
          for (Enumeration e = v.elements(); e.hasMoreElements();) {
               String key = (String)e.nextElement();
               String val = (String)ht.get(key);              
               System.out.println("Key: " + key + " Val: " + val);
          }      
     }
}


3. 세번째 방법(Key, Value 정렬)
SortedSet entries = new TreeSet(new EntryValueComparator());
entries.addAll(first.entrySet());

public class EntryValueComparator implements Comparator{
    public int compare(Object o1, Object o2) {
       return compare((Map.Entry)o1, (Map.Entry)o2);
    }
 
     public int compare(Map.Entry e1, Map.Entry e2) {
          int cf = ((Comparable)e1.getValue)().compareTo(e2.getValue());
          if (cf == 0) {
               cf = ((Comparable)e1.getKey()).compareTo(e2.getKey());
          }
          return cf;
     }
}



Posted by BAGE