1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Collections.sort实现倒序汉字拼音排序 默认是按照正序进行汉字拼音排序MYSQL语句支

Collections.sort实现倒序汉字拼音排序 默认是按照正序进行汉字拼音排序MYSQL语句支

时间:2023-11-18 11:42:45

相关推荐

Collections.sort实现倒序汉字拼音排序 默认是按照正序进行汉字拼音排序MYSQL语句支

前言:

需求上遇到过,业务希望一些下拉框,按照汉字拼音的顺序来进行展示,需要对下拉框的List进行排序。

特别注意:

Collections.reverse()方法是将数据倒置,并非倒序直接排序。

倒序排序时要先正序排序后进行倒置,获取倒序集合,所以使用reverse要明白是排序俩次。

1、实现效果:

对于文字需要排序,针对List<Map<String,String>>没有实现正常排序,需要对List<Object>进行排序

public static <T> void sort(List<T> list, Comparator<? super T> c)

具体的实现代码如下:

List<HwTheme> hwThemeList = hwThemeDao.select(status);List<ThemeNameVo> themeNameMapList = new ArrayList<>();if (CollectionUtils.isEmpty(hwThemeList)) {return themeNameMapList;}//添加(专题名称的类别,备注,存在23个相同名称的内外部专题)hwThemeList.stream().forEach(hwTheme -> {ThemeNameVo themeNameVo = new ThemeNameVo();themeNameVo.setId(String.valueOf(hwTheme.getId()));if (Optional.ofNullable(ThemeSourceEnum.of(hwTheme.getThemeSource())).isPresent()) {themeNameVo.setThemeName("(" + ThemeSourceEnum.of(hwTheme.getThemeSource()).getDesc() + ")".concat(hwTheme.getThemeName()));} else {themeNameVo.setThemeName("(" + ThemeSourceEnum.OTHERS.getDesc() + ")".concat(hwTheme.getThemeName()));}themeNameMapList.add(themeNameVo);});Comparator comparator = Collator.getInstance(Locale.CHINA);Collections.sort(themeNameMapList, new Comparator<ThemeNameVo>() {@Overridepublic int compare(ThemeNameVo themeNameVo1, ThemeNameVo themeNameVo2) {return comparator.reversed().compare(themeNameVo1.getThemeName(), themeNameVo2.getThemeName());}});return themeNameMapList;

主要关键性代码:针对List<Object>进行排序,其他不能做处理

Comparator comparator = Collator.getInstance(Locale.CHINA);

Collections.sort(themeNameMapList, new Comparator<ThemeNameVo>() {

@Override

public int compare(ThemeNameVo themeNameVo1, ThemeNameVo themeNameVo2) {

return comparator.reversed().compare(themeNameVo1.getThemeName(), themeNameVo2.getThemeName());

}

});

同时要预防排序是,对象为空的情况!

2、达到的效果

3、注意事项:sorted对象为空的时候例外处理(与本片无关)

List<TbmConvertDscodeRate> tbmConvertDscodeRatesLog = convertDsCodeRateList.stream().sorted(Comparator.nullsLast(paring(TbmConvertDscodeRate::getDsCode))).limit(1).collect(Collectors.toList());

4、数据库Mysql实现汉字排序:

编译MySQL时使用 --with--charset=gbk 参数,这样MySQL就会直接支持中文查找和排序了(默认的是latin1)。也可以用 extra-charsets=gb2312,gbk 来加入多个字符集。

如果不想对表结构进行修改或者重新编译MySQL,也可以在查询语句的 order by 部分使用 CONVERT 函数。比如

select * from mytable order by CONVERT(chineseColumnName USING gbk);

UTF8 默认校对集是 utf8_general_ci , 它不是按照中文来的。你需要强制让MySQL按中文来排序。

select * from core_vender_info order by convert(vender_abbrev USING gbk) COLLATE gbk_chinese_ci

Collections.sort实现倒序汉字拼音排序 默认是按照正序进行汉字拼音排序MYSQL语句支持汉字排序SQL汉字排序

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。