/Users/lyon/j4p/src/collections/map/MapTest.java

1    /* 
2     * MapTest.java 
3     * 
4     * Created on December 4, 2002 
5     */ 
6     
7    package collections.map; 
8     
9    import java.util.*; 
10    
11   /** 
12    * 
13    * @author  Thomas Rowland 
14    */ 
15   public class MapTest { 
16    
17       static String IMG = "<THE_IMAGE>";  //a fake image 
18    
19       public static void main(String[] args) { 
20    
21           MapTest maptest = new MapTest(); 
22           Map hashmap = new HashMap(); 
23           Map treemap; 
24    
25           //add some data to hashmap 
26           maptest.fill(hashmap); 
27    
28           /* copy data into treemap using comparator for sorting */ 
29           treemap = maptest.toTreeMap(hashmap, StarInfo.DIST_COMPARATOR); 
30           maptest.printData(treemap); 
31    
32           /* copy data into treemap using comparator for sorting */ 
33           treemap = maptest.toTreeMap(hashmap, StarInfo.NAME_COMPARATOR); 
34           maptest.printData(treemap); 
35       } 
36    
37       private Map fill(Map map) { 
38           map.put( 
39                   new StarInfo("Sun", 0), IMG); 
40           map.put( 
41                   new StarInfo("Sirius A,B", 8.60), IMG); 
42           map.put( 
43                   new StarInfo("Alpha Centauri A,B", 4.39), IMG); 
44           map.put( 
45                   new StarInfo("Barnard's Star", 5.94), IMG); 
46           map.put( 
47                   new StarInfo("Epsilon Eridani", 10.50), IMG); 
48           map.put( 
49                   new StarInfo("Proxima Centauri", 4.22), IMG); 
50           return map; 
51       } 
52    
53       private Map toTreeMap(Map map, Comparator comp) { 
54           System.out.println("Using comparator " + comp + "\n"); 
55           Map treemap = new TreeMap(comp); 
56           treemap.putAll(map); 
57           return treemap; 
58       } 
59    
60       private void printData(Map map) { 
61           Iterator keys = map.keySet().iterator(); 
62           Iterator values = map.values().iterator(); 
63           while (keys.hasNext()) { 
64               StarInfo key = (StarInfo) keys.next(); 
65               System.out.println(key.getName()); 
66               System.out.println(key.getDistance()); 
67               System.out.println(values.next()); 
68               System.out.println(); 
69           } 
70       } 
71   }