Java 实现Map集合排序功能

来源:互联网 发布:linux只显示ip 编辑:程序博客网 时间:2024/06/05 04:17

第一步:Map中新增sort临时键

// 初始化Map集合List<Map<String, String>> columns = new ArrayList<Map<String, String>>();Map<String, String> c1 = new HashMap<String,String>();c1.put("sort", "8");c1.put("title", "www.chuweibiao.com");columns.add(c1);Map<String, String> c2 = new HashMap<String,String>();c2.put("sort", "5");c2.put("title", "www.chuweibiao.com");columns.add(c2);Map<String, String> c3 = new HashMap<String,String>();c3.put("sort", "13");c3.put("title", "www.chuweibiao.com");columns.add(c3);

第二步:进行排序

/** * Map类型元素集合排序 * @param columns * Map类型元素集合 */private void listSortingForMapTypeElement(List<Map<String, Object>> columns) {Collections.sort(columns, new Comparator<Map<String, Object>>() {public int compare(Map<String, Object> last, Map<String, Object> next) {Object lastSort = last.get("sort");Object nextSort = next.get("sort");if (lastSort == null || nextSort == null) {return 0;} else {return Integer.parseInt(String.valueOf(lastSort)) > Integer.parseInt(String.valueOf(nextSort)) ? 1 : 0;}}});}

第三步:移除临时键

/** * 移除排序临时键 * @param columns * Map类型元素集合 */private void removeSortKey(List<Map<String, Object>> columns) {for (Map<String, Object> column : columns) {column.remove("sort");}}

谁有更好的办法请拍砖指教,O(∩_∩)O谢谢~
0 0
原创粉丝点击