最近遇到一个需求,需要对一个列表数据的特定字段,比如姓名,初看应该不难,但是有什么比较快速便捷的方法,因为是Java的项目,所以想到比较火的工具框架Hutool,在Hutool官网 找到一个比较器类PinyinComparator
实验环境准备
- JDK 1.8
- SpringBoot 3.3.0
- Maven 3.3.9
- Hutool 5.7.1
- 开发工具
- IntelliJ IDEA
- smartGit
代码实现
基于jdk8的集合列表遍历,将hutool的PinyinComparator
传入即可
@Test
public void testComparator() {List<RecordDto> list = Lists.newArrayList();RecordDto record01= new RecordDto();record01.setStuName("风清扬");RecordDto record02= new RecordDto();record02.setStuName("小明");RecordDto record03= new RecordDto();record03.setStuName("杰克");list.add(record01);list.add(record02);list.add(record03);list = list.stream().sorted(Comparator.comparing(RecordDto ::getSName, new PinyinComparator())).collect(Collectors.toList());list.stream().forEach(e -> {System.out.println(e.getSName());});
}
源码实现
PinyinComparator
也是基于Comparator
接口
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//package cn.hutool.core.comparator;import java.io.Serializable;
import java.text.Collator;
import java.util.Comparator;
import java.util.Locale;public class PinyinComparator implements Comparator<String>, Serializable {private static final long serialVersionUID = 1L;final Collator collator;public PinyinComparator() {this.collator = Collator.getInstance(Locale.CHINESE);}public int compare(String o1, String o2) {return this.collator.compare(o1, o2);}
}