import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; public class MapSort { /**此方法实现Map排序*/ public static Map getQueryMap(Map oldMap){ ArrayList<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(oldMap.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Entry<java.lang.String, Integer> arg0, Entry<java.lang.String, Integer> arg1) { return arg0.getValue() - arg1.getValue(); } }); Map newMap = new LinkedHashMap(); for (int i = 0; i < list.size(); i++) { newMap.put(list.get(i).getKey(), list.get(i).getValue()); } return newMap; } }
//这是定时器,在此方法里直接调用map排序方法
public void run(){ System.out.println("心跳定时器"); long obtainTime=System.currentTimeMillis()/1000; int currentTime=(int) obtainTime; Map map=new HashMap(); map=CacheTime.getInstance().getCacheItems(); map= mapsort.getQueryMap(map); Iterator<Map.Entry<String,String>> it=map.entrySet().iterator(); while(it.hasNext()){ Map.Entry<String,String> entry=it.next(); String key=String.valueOf(entry.getKey()); String value=String.valueOf(entry.getValue()); int dateTime=Integer.parseInt(value); int difTime=(currentTime-dateTime)/60; if(difTime>1){ it.remove(); } } }
此方法,本人用于在定时器里面使用,场景:某类方法里面,将用户token存到全局map缓存里面,在定时器里获取map,并排序,如果是掉线这样的吗,直接从map剔除,排序会将效率提高。