Java将list或者list集合根据指定字段排序

今天项目中用到了,特记录一下

一. List<Map>

如果 item.get(sortField) 有时间,有数字的时候直接toString(),数组结果的排序结果可能不正确

List<Map<String, Object>> resourceCatalogFrontVoList = resourceMapper.selectPublishResourceCatalogList(keyWord, sysId, shareType, openAttribute,
classifyId, resourceType, page);
//排序
Comparator<Map<String, Object>> comparator = Comparator.comparing(item -> item.get(sortField).toString());
if (FrontConstant.SORT_TYPE_ASC == sortType){
//升序
resourceCatalogFrontVoList.sort(comparator);
}else {
resourceCatalogFrontVoList.sort(comparator.reversed());
}
//分页
return page.setRecords(resourceCatalogFrontVoList);

补充

if (FrontConstant.SORT_TYPE_ASC == sortType){
//升序
Collections.sort(resourceCatalogFrontVoList, Comparator.comparing(
item -> item.get(sortField).toString()));
}else {
Collections.sort(resourceCatalogFrontVoList, Comparator.comparing(
item -> item.get(sortField).toString(), Comparator.reverseOrder()));
}

二.List<entity>


List<ResMessageVo> messageVoList = messageMapper.selectUnReadMessage(null, null, null, MessageConstant.MESSAGE_TYPE_MOUNT_RESOURCE_RESULT);

//排序
        Comparator<ResMessageVo> comparator = Comparator.comparing(item -> item.getCreateTime());
if (FrontConstant.SORT_TYPE_ASC == sortType){
//升序
messageVoList.sort(comparator);
}else {
messageVoList.sort(comparator.reversed());
}
上一篇:vs2012配置使用entity framework 6


下一篇:perl IDE