您的位置:首页 > 其它

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

2009-07-23 10:04 513 查看
HashMap中的对象根据成员进行自定义排序

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

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

1. 定义CacheObj类

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

/*

* Created on 2003-3-5

*/

package com.cache;

/** * @author Weidong * */

public class CacheObj {

int cachedCounter;

Object cacheObj = null;

/**

* @return Returns the cacheObj.

*/

public Object getCacheObj() {

return cacheObj;

}

/**

* @param cacheObj

* The cacheObj to set.

*/

public void setCacheObj(Object cacheObj) {

this.cacheObj = cacheObj;

}

/**

* @return Returns the cachedCounter.

*/

public int getCachedCounter() {

return cachedCounter;

}

/**

* @param cachedCounter

* The cachedCounter to set.

*/

public void setCachedCounter(int cachedCounter) {

this.cachedCounter = cachedCounter;

}

}

2. 自定义HotItemComparator

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

正序:return obj1.getCachedCounter() - obj2.getCachedCounter();

倒序:return obj2.getCachedCounter() - obj1.getCachedCounter();

package com.cache;

import java.util.Comparator;

/**

* @author Weidong

*/

public final class HotItemComparator implements Comparator {

/*

* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)

*/

public int compare(Object arg0, Object arg1) {

CacheObj obj1 = (CacheObj) arg0;

CacheObj obj2 = (CacheObj) arg1;

return obj1.getCachedCounter() - obj2.getCachedCounter();

}

}

3. 测试用例

定义变量:public static final Comparator HOT_ITEM = new HotItemComparator();

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

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

package com.cache;

import java.util.ArrayList;

import java.util.Collections;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

/**

* @author Weidong

*/

public class TestBean {

public static final Comparator HOT_ITEM = new HotItemComparator();

public static void sortMap() {

Map caches = new HashMap();

CacheObj s1 = new CacheObj();

s1.setCachedCounter(2);

CacheObj s2 = new CacheObj();

s2.setCachedCounter(3);

CacheObj s3 = new CacheObj();

s3.setCachedCounter(1);

caches.put("1", s1);

caches.put("2", s2);

caches.put("3", s3);

List sortList = new ArrayList();

sortList.addAll(caches.values());

Collections.sort(sortList, HOT_ITEM);

Iterator iter = sortList.iterator();

while (iter.hasNext()) {

CacheObj s = (CacheObj) iter.next();

System.out.println("counter is "+s.getCachedCounter());

}

}

public static void main(String[] args) {

sortMap();

}

}

输出:文中用正序

counter is 1

counter is 2

counter is 3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: