Selaa lähdekoodia

排序使用代码排序

chen 5 vuotta sitten
vanhempi
commit
3f4a098759

+ 32 - 10
ssj-mybatis-service-impl/src/main/java/com/ssj/utils/SortByChineseUtil.java

@@ -1,6 +1,10 @@
 package com.ssj.utils;
 import com.ssj.bean.sys.sort.domain.Sort;
 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;
 
 import java.text.Collator;
 import java.util.*;
@@ -55,21 +59,38 @@ public class SortByChineseUtil {
 
     public static List sortByChinese(List<String> list) {
         TreeMap map = new TreeMap();
-        String[] s = new String[list.size()];
         for (String str : list) {
-            char[] chars = str.toCharArray();
-            if (Character.toString(chars[0]).matches("[\\u4E00-\\u9FA5]+")) {
-                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(chars[0]);
-                map.put(setMapKey(map,Character.toString(pinyinArray[0].charAt(0))), str);
-            } else if (Character.toString(chars[0]).matches("[a-zA-Z]+")) {
-                map.put(setMapKey(map,Character.toString(chars[0]).toLowerCase()), str);
-            } else {
-                map.put(setMapKey(map,Character.toString(chars[0])), str);
-            }
+            map.put(ToPinyin(str), str);
         }
         List<String> result = new ArrayList<String>(map.values());
         return result;
     }
+
+    /**
+     * 汉字转为拼音
+     * @param chinese
+     * @return
+     */
+     public static String ToPinyin(String chinese){
+         String pinyinStr = "";
+         char[] newChar = chinese.toCharArray();
+         HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
+         defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
+         defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
+         for (int i = 0; i < newChar.length; i++) {
+             if (newChar[i] > 128) {
+                 try {
+                     pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
+                 } catch (BadHanyuPinyinOutputFormatCombination e) {
+                     e.printStackTrace();
+                 }
+             }else{
+                 pinyinStr += newChar[i];
+             }
+         }
+         return pinyinStr.toLowerCase();
+     }
+
     /**
      *  解决key一样会覆盖的问题
      */
@@ -91,5 +112,6 @@ public class SortByChineseUtil {
         map.put(8,"it");
         map.put(99,",");
         System.out.println(SortByChineseUtil.sortByValue(map));
+        System.out.println(SortByChineseUtil.ToPinyin("1+1天天练A(2020)"));
     }
 }