java Map的访问方法备忘,Comparator例子

1.把Map中的Key或Value转化为数组

HashMap ssMap = new HashMap(); 

Counter counters[] = new Counter[ssMap.size()]; 
ssMap.values().toArray(counters); //转化,counters不需实例化
Arrays.sort(counters,new DfComparator());//排序

2. Comparator 实例

继承Comparator也可以实现排序,但相对Comparable接口更加灵活,用不同的Comparator实例可以实现不同的排序方法

class DfComparator implements Comparator
{
 public int compare(Object o1, Object o2) {
  // TODO Auto-generated method stub
  Counter c1 = (Counter)o1;
  Counter c2 = (Counter)o2;

  return c2.df - c1.df;
 }
 public boolean equals(Object obj)
 {
  return true;
 }
 
}

3.Map访问语句备忘

 public static void print(Map map)
 {
  Set set = map.entrySet();
  Iterator iter = set.iterator();
  while(iter.hasNext())
  {
   Map.Entry entry = (Map.Entry)iter.next();
   entry.getKey();
   entry.getValue();
  }
 }

 

你可能感兴趣的:(java)