Map是集合的存放顺序是按哈希值定的,有时候不是我们需要的,当想要一个按自己规定顺序存放顺序,可以用LinkedHashMap,这里自己把LinkedHashMap封装了一次
package test.com.reflect; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; public class MapUtill { public static void main(String[] args) { Map<Object,Object> map = newMap("{‘id‘:‘主键‘,‘age‘:‘年龄‘,‘name‘:‘姓名‘,‘className‘:‘班级‘,‘area‘:{‘code‘:‘代码‘,‘name‘:‘地名‘,‘as‘:‘的‘},‘strs‘:‘发大发‘} ",true); // map.putAll(m); System.err.println(map); } public static Map<Object,Object> newMap(){ return new HashMap<Object,Object>(); } public static Map<Object,Object> newMap(String txt){ return newMap(txt,false); } /** * @param txt Map字符串 * @param sort 是否按txt 排序生成 * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static Map<Object,Object> newMap(String txt,Boolean sort){ com.alibaba.fastjson.JSONObject jsonObj = com.alibaba.fastjson.JSONObject.parseObject(txt); if(!sort) { return (Map)jsonObj; } final String t = txt; // Map<String, Object> rs = sort(jsonObj,new Comparator<String>() { // @Override // public int compare(String o1, String o2) { // if(t.indexOf(o1)> t.indexOf(o2)) { // return 1; // } // if(t.indexOf(o1)< t.indexOf(o2)) { // return -1; // } // return 0; // } // }); Object[] arrKeys = sortKeys((Map)jsonObj,new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { if(t.indexOf((String)o1)> t.indexOf((String)o2)) { return 1; } if(t.indexOf((String)o1)< t.indexOf((String)o2)) { return -1; } return 0; } }); LinkedHashMap<String, Object> rs = new LinkedHashMap<>(); for (int i = 0; i < arrKeys.length; i++) { Object v = jsonObj.get(arrKeys[i]); if(v instanceof Map) { int key = txt.indexOf((String)arrKeys[i]); int index1 = txt.indexOf("{", key); int index2 = txt.indexOf("}", index1); v = newMap(txt.substring(index1,index2+1),false); } rs.put((String)arrKeys[i], v); } return (Map)rs; } public static <K, V> Map<K,V> sort(Map<K,V> map,Comparator<K> comparator){ LinkedHashMap<K,V> rs = new LinkedHashMap<K,V>(); K[] arrKeys = sortKeys(map,comparator); for (K k : arrKeys) { rs.put(k, map.get(k)); } return rs; } @SuppressWarnings("unchecked") private static <K, V> K[] sortKeys(Map<K,V> map,Comparator<K> comparator) { Set<K> keys = map.keySet(); K[] arr = (K[])(new Object[keys.size()]); K[] arrKeys = keys.toArray(arr); Arrays.sort(arrKeys,comparator); return arrKeys; } }
原文地址:https://www.cnblogs.com/jonrain0625/p/11191516.html
时间: 2024-10-15 17:54:07