1. 程式人生 > 實用技巧 >List<HashMap>排序,List記憶體分頁

List<HashMap>排序,List記憶體分頁

你有時候是否覺得Java的排序是否有些麻煩,迭代的方式程式碼有些多呢?

 Collections.sort(list, new Comparator<HashMap>() {
                        public int compare(HashMap o1, HashMap o2) {
                            Integer name1 = Integer.valueOf(o1.get("tm_linenumber").toString());//name1是從你list裡面拿出來的一個,根據你需要排序的欄位進行設定相應的型別,如果需要倒序就把兩個物件對調一下
Integer name2 = Integer.valueOf(o2.get("tm_linenumber").toString()); //name1是從你list裡面拿出來的第二個name return name1.compareTo(name2); } });

記憶體分頁,請看下面程式碼

Integer fromIndex = (pageIndex - 1) * pageSize;
Integer toIndex = fromIndex + pageSize;
Iterator<Map.Entry<String, List<HashMap>>> iterator = resultMap.entrySet().iterator();
HashMap<String, List<HashMap>> hashMap = new HashMap<>();
while (iterator.hasNext()) {
Map.Entry<String, List<HashMap>> entry = iterator.next();
List<HashMap> list = entry.getValue();
if (fromIndex > (list.size() - 1)) {
hashMap.put(entry.getKey(), new ArrayList<>());
} else {
//regin 資料記憶體排序 xun-yu.she

//list.get(1).put("tm_linenumber", "7");
//list.get(2).put("tm_linenumber", "2");
//list.get(5).put("tm_linenumber", "a");
try {
Collections.sort(list, new Comparator<HashMap>() {
public int compare(HashMap o1, HashMap o2) {
Integer name1 = Integer.valueOf(o1.get("tm_linenumber").toString());//name1是從你list裡面拿出來的一個
Integer name2 = Integer.valueOf(o2.get("tm_linenumber").toString()); //name1是從你list裡面拿出來的第二個name
return name1.compareTo(name2);
}
});

} catch (Exception e) {
//排序失敗
restResult.setMsg("sort error " + e.getMessage());
}
//endregion
List<HashMap> hashMaps = list.subList(fromIndex, toIndex > (list.size() - 1) ? list.size() : toIndex);
hashMap.put(entry.getKey(), hashMaps);
}
}