1. 程式人生 > >TreeMap Comparator按照首字母排序

TreeMap Comparator按照首字母排序

       /**
	 * @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!");
		}
	}