java对集合中的某个类的属性按首字母分组排序(可直接使用)
java对集合中的某个类的属性按首字母分组排序(可直接使用)
直接上代码
一、导入jar包
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
PinYinUtil工具类
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
public class PinYinUtil {
//将字符串转成拼音
public static String getPinYin(String chinese){
char[] spell = chinese.toCharArray();
String pinYin = "";
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for(int i= 0; i<spell.length; i++){
if(spell[i]>128){
try{
pinYin += PinyinHelper.toHanyuPinyinStringArray(spell[i],defaultFormat)[0];
}catch(BadHanyuPinyinOutputFormatCombination e){
e.printStackTrace();
}
}else{
pinYin += spell[i];
}
}
return pinYin;
}
}
排序分组工具类
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
@Slf4j
public class SortByLetterAscUtils {
/**
*
* @param object 一个集合
* @param clazz 集合存放的类
* @param field 要排序的类的字段,字段的getXyz() X要大写
* @return
* @throws Exception
*/
public static Map<String,Object> sortByLetterAsc(Object object, Class clazz, String field) throws Exception {
if(object instanceof List){
List<Object> list = (List<Object>) object;
Class<?> c = Class.forName(clazz.getName());
Object o = c.newInstance();
Map<String,Object> map = new HashMap<String,Object>();
//按拼音首字母表排序
Map<String, ArrayList<Object>> letterMap = new TreeMap<String,ArrayList<Object>>(new MapSortUtil().getMapKeyComparator());
if(!list.isEmpty()) {
for (Object t : list) {
o = t;
String pinYinFirstLetter = getFieldValue(field, o);
if(!letterMap.containsKey(pinYinFirstLetter) && pinYinFirstLetter.matches("[A-Z]")){
letterMap.put(pinYinFirstLetter, new ArrayList<Object>());
}
}
Iterator<Map.Entry<String, ArrayList<Object>>> entries = letterMap.entrySet().iterator();
while(entries.hasNext()){
Entry<String, ArrayList<Object>> next = entries.next();
ArrayList<Object> listTemp = new ArrayList<Object>();
for (Object t : list) {
o = t;
String pinYinFirstLetter = getFieldValue(field, o);
if(!StringUtils.isEmpty(pinYinFirstLetter) && next.getKey().equals(pinYinFirstLetter)){
listTemp.add(t);
}
}
next.getValue().addAll(listTemp);
}
log.debug("对letterMap按照升序排序,#放到最后");
}
ArrayList<Object> listTemp2 = new ArrayList<Object>();
if(!list.isEmpty()){
for (Object t : list) {
o = t;
String pinYinFirstLetter = getFieldValue(field, o);
if (!pinYinFirstLetter.matches("[A-Z]")) {
listTemp2.add(t);
}
}
if(!listTemp2.isEmpty()){
letterMap.put("#", listTemp2);
}
}
//保证map排序后的顺序不
JSONObject jsonObject = new JSONObject(true);
jsonObject.put("key", letterMap);
map.put("data",jsonObject);
return map;
}else {
log.info("转化为list失败");
return null;
}
}
/**
* 获取传递字段的属性值
* @param field 字段名 要大写 比如"Name"
* @param o
* @return
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private static String getFieldValue(String field, Object o)
throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
String name = field.substring(0, 1).toUpperCase() + field.substring(1);
Method method = o.getClass().getMethod("get"+name);
//获取字段属性值
String value = (String) method.invoke(o);
//取首字母大写返回
String pinYinFirstLetter = PinYinUtil.getPinYin(value).substring(0,1).toUpperCase();
return pinYinFirstLetter;
}
}
辅助工具类
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class MapSortUtil {
/** * 使用 Map按key进行排序
* @param map * @return
*/
public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String,Object> sortMap = new TreeMap<String, Object>(new MapKeyComparator());
sortMap.putAll(map);
return sortMap;
}
public MapKeyComparator getMapKeyComparator() {
return new MapKeyComparator();
}
}
class MapKeyComparator implements Comparator<String> {
@Override
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
}
测试
import com.dql.user.entity.User;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Slf4j
public class TestPinyin {
public static void main(String[] args) {
log.info("测试开始------------");
List<User> list = new ArrayList<>();
list.add(new User("张三",20,"男","12345678910"));
list.add(new User("李四",22,"男","12345678910"));
list.add(new User("王五",24,"男","12345678910"));
list.add(new User("杜甫",560,"男","12345678910"));
list.add(new User("!啊哈",560,"男","12345678910"));
log.info("封装对象完成--------------");
Map<String, Object> map = null;
try {
log.info("开始分组排序---------------------------");
map = SortByLetterAscUtils.sortByLetterAsc(list, User.class, "Name");
} catch (Exception e) {
log.error("分组排序错误------------");
e.printStackTrace();
}
if (map == null){
System.out.println("分组排序失败--------------------");
}else System.out.println(map.toString());
}
}
测试结果
10:38:28.903 [main] INFO com.dql.common.utils.TestPinyin - 测试开始------------
10:38:28.905 [main] INFO com.dql.common.utils.TestPinyin - 封装对象完成--------------
10:38:28.905 [main] INFO com.dql.common.utils.TestPinyin - 开始分组排序---------------------------
10:38:28.928 [main] DEBUG com.dql.common.utils.SortByLetterAscUtils - 对letterMap按照升序排序,#放到最后
{data={“key”:{"#":[{“age”:560,“name”:"!啊哈",“sex”:“男”,“tel”:“12345678910”}],“D”:[{“age”:560,“name”:“杜甫”,“sex”:“男”,“tel”:“12345678910”}],“L”:[{“age”:22,“name”:“李四”,“sex”:“男”,“tel”:“12345678910”}],“W”:[{“age”:24,“name”:“王五”,“sex”:“男”,“tel”:“12345678910”}],“Z”:[{“age”:20,“name”:“张三”,“sex”:“男”,“tel”:“12345678910”}]}}}
本文地址:https://blog.csdn.net/weixin_48229907/article/details/107685380
上一篇: 诸葛恪是个怎样的人?为何会被孙权重用呢?
下一篇: 多种获取远程连接access数据库的方法