java系列之-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> listMap = null;
		
		/*以首字母KEY排序*/
		Map keymap = new TreeMap(new Comparator() {
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}
		});
		
		try {
			/*接收查询结果*/
			listMap = wikiService.loadPartsTypes();
			
			/*遍历列表*/
			for(Map 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> partList = (Set>) keymap
							.get(firstSpell);
					
					/*空值判断*/
					if(null == partList){
						partList = new HashSet>();
					}
					
					/*空值判断*/
					if(partList.size() > 0){
						partList.add(map);
					}else{
						partList.add(map);
						keymap.put(firstSpell, partList);
					}
				}
			}
			
			/*转换数据格式*/
			Set> entrySet= keymap.entrySet();
			List> finalSet = new ArrayList>();
			for (Entry entry : entrySet) {
				Set> setMap = (Set>) entry.getValue();
				for(Map map : setMap){
					finalSet.add(map);
				}
			}
			return success("Load partsTypes success.", finalSet);
		} catch (Exception e) {
			logger.error(e); e.printStackTrace();
			return error("System error!");
		}
	}

 

你可能感兴趣的:(Java后台)