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);
}
}
原文地址:https://www.cnblogs.com/shexunyu/p/13343384.html