HashMap中的对象根据成员进行自定义排序

http://tech.ddvip.com   2008年06月12日    社区交流

内容摘要:Map是Java中最常用的存储对象的集合类之一,存储在HashMap中的对象在取出时是无序的,下文以示例介绍了如果对HashMap中存储的对象根据成员进行自定义排序。

  Map是Java中最常用的存储对象的集合类之一,存储在HashMap中的对象在取出时是无序的,下文以示例介绍了如果对HashMap中存储的对象根据成员进行自定义排序。

  应用说明:计算缓存对象的点击次数按次数排序输出。

  1.定义CacheObj类

  定义了一个简单的对象,这个对象将存储在一个HashMap中,希望根据CacheObj中的整型成员变量cachedCounter进行排序输出。

/*
*Createdon2003-3-5
*/
packagecom.cache;
/** *@authorWeidong* */
publicclassCacheObj{
 intcachedCounter;
 ObjectcacheObj=null;
 /**
 *@returnReturnsthecacheObj.
 */
 publicObjectgetCacheObj(){
  returncacheObj;
 }
 /**
 *@paramcacheObj
 *     ThecacheObjtoset.
 */
 publicvoidsetCacheObj(ObjectcacheObj){
  this.cacheObj=cacheObj;
 }
 /**
 *@returnReturnsthecachedCounter.
 */
 publicintgetCachedCounter(){
  returncachedCounter;
 }
 /**
 *@paramcachedCounter
 *     ThecachedCountertoset.
 */
 publicvoidsetCachedCounter(intcachedCounter){
  this.cachedCounter=cachedCounter;
 }
}

  2.自定义HotItemComparator

  HotItemComparator实现了Comparator接口,实现的方法非常简单就是根据cachedCounter进行比较返回比较结果

  正序:returnobj1.getCachedCounter()-obj2.getCachedCounter();

  倒序:returnobj2.getCachedCounter()-obj1.getCachedCounter();

packagecom.cache;
importjava.util.Comparator;
/**
*@authorWeidong
*/
publicfinalclassHotItemComparatorimplementsComparator{
  /*
  *@seejava.util.Comparator#compare(java.lang.Object,java.lang.Object)
  */
  publicintcompare(Objectarg0,Objectarg1){
    CacheObjobj1=(CacheObj)arg0;
    CacheObjobj2=(CacheObj)arg1;
    returnobj1.getCachedCounter()-obj2.getCachedCounter();
  }
}

  3.测试用例

  定义变量:publicstaticfinalComparatorHOT_ITEM=newHotItemComparator();

  将HashMap追加到List对象sortList中:sortList.addAll(caches.values());

  对sorList应用HOT_ITEM排序:Collections.sort(sortList,HOT_ITEM);

packagecom.cache;
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
/**
*@authorWeidong
*/
publicclassTestBean{
  publicstaticfinalComparatorHOT_ITEM=newHotItemComparator();
  publicstaticvoidsortMap(){
    Mapcaches=newHashMap();
    CacheObjs1=newCacheObj();
    s1.setCachedCounter(2);
    CacheObjs2=newCacheObj();
    s2.setCachedCounter(3);
    CacheObjs3=newCacheObj();
    s3.setCachedCounter(1);
    caches.put("1",s1);
    caches.put("2",s2);
    caches.put("3",s3);
    ListsortList=newArrayList();
    sortList.addAll(caches.values());
    Collections.sort(sortList,HOT_ITEM);
    Iteratoriter=sortList.iterator();
    while(iter.hasNext()){
      CacheObjs=(CacheObj)iter.next();
      System.out.println("counteris"+s.getCachedCounter());
    }
  }
  publicstaticvoidmain(String[]args){
    sortMap();
  }
}

  输出:文中用正序

  counteris1

  counteris2

  counteris3

责编:豆豆技术应用

正在加载评论...