实现对存放了Map集合的ArrayList的排序(按照map中某个字段比较)

package com.vtstar.sct.desktop.clients.FeedingLine21.swingUI.demos;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.TreeSet;

/**
* Created by xuming on 2018/1/29.
* 实现对存放了Map的ArrayList的排序。(规则是按照map中的字段)
* 调用:
* ArrayList<Map<String,Object>> sortList = new SortMapsByMapSomeField().getSortList(乱序的List);
*/
public class SortMapsByMapSomeField implements Comparable<SortMapsByMapSomeField>{
private Map<String,Object> map;

public SortMapsByMapSomeField(){
}

public SortMapsByMapSomeField(Map<String,Object> map){
this.map = map;
}

//本例中按照map中的一个Date类型的字段planDatefrom排序
@Override
public int compareTo(SortMapsByMapSomeField objMap) {
Date thisDate = (Date) this.map.get("planDatefrom");
Date objDate = (Date)objMap.map.get("planDatefrom");
if(thisDate.after(objDate)){
return 1;
}else{
return -1;
}
}

private Map<String,Object> getMap(){
return this.map;
}

/******************
* 接收一个ArrayList<Map<String,Object>> 按照其中的map中的某一个字段对该list排序。
* 返回一个有序的ArrayList<Map<String,Object>>
*/
public ArrayList<Map<String,Object>> getSortList(ArrayList<Map<String,Object>> maps){
ArrayList<SortMapsByMapSomeField> sortMapsLists = mapToSortTreeSet(maps);
TreeSet<SortMapsByMapSomeField> sortMaps = new TreeSet<>();
for(SortMapsByMapSomeField map : sortMapsLists){
sortMaps.add(map);
}
ArrayList<Map<String,Object>> sorList = sortMapToMap(sortMaps);
return sorList;
}

private ArrayList<SortMapsByMapSomeField> mapToSortTreeSet(ArrayList<Map<String,Object>> maps){
ArrayList<SortMapsByMapSomeField> list = new ArrayList<>();
for(Map map :maps){
list.add(new SortMapsByMapSomeField(map));
}
return list;
}

private ArrayList<Map<String,Object>> sortMapToMap(TreeSet<SortMapsByMapSomeField> sortMaps){
ArrayList<Map<String,Object>> list = new ArrayList<>();
for(SortMapsByMapSomeField sortMap : sortMaps){
list.add(sortMap.getMap());
}
return list;
}
}

posted on 2018-01-29 17:34  笑明子  阅读(450)  评论(0编辑  收藏  举报

导航