HashMap按照value值进行排序

时间:2022-10-13 19:14:58
今天的工作中需要对HashMap中的value值进行从大到小排序,并取出前6个值,持久化到properties文件中,代码如下
Map<Camera,Long> commonCamera = new HashMap<Camera,Long>();
tt = new TimerTask(){
@Override
public void run() {
try {
Properties prop = new Properties();
OutputStream out = new FileOutputStream("commonUse.properties");
List<Map.Entry<Camera, Long>> list = new ArrayList<Map.Entry<Camera,Long>>(commonCamera.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Camera, Long>>(){
@Override
public int compare(Entry<Camera, Long> o1,
Entry<Camera, Long> o2) {
//按从大到小排序
return (int) (o2.getValue() - o1.getValue());
}
});
for(int i = 0; i <(list.size()>12?12:list.size()); i++){
prop.setProperty(list.get(i).getKey().getDepartment().getNo()+"", list.get(i).getValue().toString());
}
prop.store(out, "");
logger.info("6小时重复任务:向commonUse.properties文件写入‘常用摄像头’信息");
} catch (Exception e) {
e.printStackTrace();
}
}
};
timer.schedule(tt, 0, 1000*60*60*6);

;