TreeMap Comparator按照首字母排序

时间:2022-12-04 02:52:26
       /**
* @Modified by FANGYUKANG
* @Description 查询配件类型列表
* @return {@link JsonView}
*
* URL local
* http://127.0.0.1:8080/admin/wiki/loadPartsTypes
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/loadPartsTypes", method = RequestMethod.GET)
public JsonView loadPartsTypes() {

/*封装查询结果*/
List<Map<String, Object>> listMap = null;

/*以首字母KEY排序*/
Map<String,Object> keymap = new TreeMap<String, Object>(new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});

try {
/*接收查询结果*/
listMap = wikiService.loadPartsTypes();

/*遍历列表*/
for(Map<String, Object> map : listMap){

/*空值判断*/
if(null != map.get("partTypeName")){

/*取得配建项目名*/
String partTypeName = map.get("partTypeName").toString();

/*取得配建项目名拼音首字母大写*/
String partTypeNameFirstSpell = PingYinUtil.getFirstSpell(partTypeName);
char[] firstSpellArray = partTypeNameFirstSpell.toCharArray();
String firstSpell = String.valueOf(firstSpellArray[0]);

/*验证项目名首字母是否是以数字开头*/
java.util.regex.Pattern pattern = java.util.regex.Pattern
.compile("^[0-9]{1}$");
java.util.regex.Matcher m = pattern.matcher(firstSpell);

/*满足首字母开头则以数字拼音首字母为准*/
if (m.matches()) {
switch (Integer.valueOf(String.valueOf(firstSpell))) {
case 0: firstSpell = "L"; break;
case 1: firstSpell = "Y"; break;
case 2: firstSpell = "E"; break;
case 3: firstSpell = "S"; break;
case 4: firstSpell = "S"; break;
case 5: firstSpell = "W"; break;
case 6: firstSpell = "L"; break;
case 7: firstSpell = "Q"; break;
case 8: firstSpell = "B"; break;
case 9: firstSpell = "J"; break;
}
}

/*根据品牌索引首字母在KEYMAP中取得对应的品牌信息*/
Set<Map<String, Object>> partList = (Set<Map<String, Object>>) keymap
.get(firstSpell);

/*空值判断*/
if(null == partList){
partList = new HashSet<Map<String, Object>>();
}

/*空值判断*/
if(partList.size() > 0){
partList.add(map);
}else{
partList.add(map);
keymap.put(firstSpell, partList);
}
}
}

/*转换数据格式*/
Set<Entry<String, Object>> entrySet= keymap.entrySet();
List<Map<String, Object>> finalSet = new ArrayList<Map<String, Object>>();
for (Entry<String, Object> entry : entrySet) {
Set<Map<String, Object>> setMap = (Set<Map<String, Object>>) entry.getValue();
for(Map<String, Object> map : setMap){
finalSet.add(map);
}
}
return success("Load partsTypes success.", finalSet);
} catch (Exception e) {
logger.error(e); e.printStackTrace();
return error("System error!");
}
}