像这种代码如何优化 根据字段排序

2021-07-20 17:25:08 +08:00
 followyourheart

不能直接在数据库排序 数据要从数据库查出组装,然后排序

1793 次点击
所在节点    程序员
9 条回复
CEBBCAT
2021-07-20 18:00:27 +08:00
看得不是很懂,但我之前有一次排序也是很头大,那次我是通过算分来间接排序的,把所有的值都落在 int 上,然后按照顺序读出
potatowish
2021-07-20 19:02:16 +08:00
维护一个枚举类型,column,sortType,Comparator,isReversed, 再写一个方法根据 column sortType isReversed 匹配到唯一的枚举,另外一个方法根据枚举来动态处理数据
potatowish
2021-07-20 19:03:43 +08:00
@potatowish 采用这种方式,不需要在业务类写大量判断,只需要维护这个枚举中的映射关系就好了
ForkNMB
2021-07-20 19:59:22 +08:00
逆序不要用 reversed 噢,没啥必要,直接在比较器里传参就行,list.stream().sorted(Comparator.comparing(类::属性一,Comparator.reverseOrder()));
至于优化的话,维护一个枚举类,维护不同种类的比较器即可(比较器的字段类型,是否逆序这些信息)
oneisall8955
2021-07-20 20:27:42 +08:00
枚举类+抽象方法 简简单单又美观
xiang0818
2021-07-21 16:48:12 +08:00
```
package com.netease.ehr.mbo.model.enums;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author xiang0818
* @date 2021-07-21 16:06
*/
public enum SortEnum {

/**
* .
*/
COUNT("count", SckPriceVo::getCount),
;
private final String column;


private final Function<SckPriceVo, Integer> functionGen;


SortEnum(String column, Function<SckPriceVo, Integer> functionGen) {
this.column = column;
this.functionGen = functionGen;
}

public String getColumn() {
return column;
}

private Comparator<SckPriceVo> getComparing(String sortType) {
if (sortType.equals("1")) {
return Comparator.comparing(functionGen);
} else if (sortType.equals("2")) {
return Comparator.comparing(functionGen).reversed();
}
throw new RuntimeException("error");
}

private static SortEnum getByColumn(String column) {
for (SortEnum value : SortEnum.values()) {
if (value.column.equals(column)) {
return value;
}
}
throw new RuntimeException("error");
}

public static List<SckPriceVo> getSort(List<SckPriceVo> sckPriceVoList, String column, String sortType) {
return sckPriceVoList.stream().sorted(SortEnum.getByColumn(column).getComparing(sortType)).collect(Collectors.toList());
}
}
EAFA0
2021-07-21 20:36:43 +08:00
简单抽象一下? 写个封装函数?
``` json
public static sort(Collection<T> collection, Function<T, Comparable> getField, boolean isReserve)
```
大概这个样子?
EAFA0
2021-07-21 20:37:27 +08:00
@EAFA0 问题挺多, 大概意思 get 到就行?
siweipancc
2021-07-26 08:59:37 +08:00
封装一个动态排序器,由前段调用时候生成。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/790656

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX