3

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

 2 years ago
source link: https://www.v2ex.com/t/790656
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  程序员

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

  followyourheart · 5 小时 52 分钟前 · 451 次点击

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

5 条回复    2021-07-20 20:27:42 +08:00

CEBBCAT

CEBBCAT   5 小时 16 分钟前 via Android

看得不是很懂,但我之前有一次排序也是很头大,那次我是通过算分来间接排序的,把所有的值都落在 int 上,然后按照顺序读出

potatowish

potatowish   4 小时 15 分钟前 via iPhone

维护一个枚举类型,column,sortType,Comparator,isReversed, 再写一个方法根据 column sortType isReversed 匹配到唯一的枚举,另外一个方法根据枚举来动态处理数据

potatowish

potatowish   4 小时 13 分钟前 via iPhone

@potatowish 采用这种方式,不需要在业务类写大量判断,只需要维护这个枚举中的映射关系就好了

ForkNMB

ForkNMB   3 小时 18 分钟前

逆序不要用 reversed 噢,没啥必要,直接在比较器里传参就行,list.stream().sorted(Comparator.comparing(类::属性一,Comparator.reverseOrder()));
至于优化的话,维护一个枚举类,维护不同种类的比较器即可(比较器的字段类型,是否逆序这些信息)

oneisall8955

oneisall8955   2 小时 49 分钟前 via Android

枚举类+抽象方法 简简单单又美观

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK