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

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

一. List

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

List> resourceCatalogFrontVoList = resourceMapper.selectPublishResourceCatalogList(keyWord, sysId, shareType, openAttribute,
                classifyId, resourceType, page);
        //排序
        Comparator> 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

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

//排序
        Comparator comparator = Comparator.comparing(item -> item.getCreateTime());
        if (FrontConstant.SORT_TYPE_ASC == sortType){
            //升序
            messageVoList.sort(comparator);
        }else {
            messageVoList.sort(comparator.reversed());
        }

 

转载于:https://www.cnblogs.com/cailijuan/p/11412722.html

你可能感兴趣的:(Java将list或者list集合根据指定字段排序)