hashmap和数组相互转换的问题

原来的数据类型是hashmap,里面的值是名称对应值的,转换为数组后,数组见面全是值了,而没有名称,现在再转换成map,怎么再把他的名称一一对应起来啊?求好的思路方式?

Map map = new HashMap();
map.put("1", "value1");
map.put("2", "value2");
map.put("3", "value3");
String key[] = new String[];
String value[] = new String[];
System.out.println("通过Map.entrySet遍历key和value");
for (Map.Entry entry : map.entrySet()) {
key[key.length]=key;
value[value.length]=map.get(key);
System.out.println("key= "+ key + " and value= " + map.get(key));
//然后将key,value分别存到两个数组里面
}
或者将map里面的一组元素看作一个小数组,直接存到一个数组里面
String mapArray[] = new String[];
for (String key : map.keySet()) {
String addMap[] = new String[];
addMap.[0]=key;
addMap.[1]= map.get(key);
key[key.length]=addMap;
System.out.println("key= "+ key + " and value= " + map.get(key));
}

把entryset转为数组,数组每个元素中key和value都有了。

map.keySet().toArray. 获取key数组
map.values().toArray 获取value数组
key数组的第i个元素 对应value数组的第i个值 就可以转换回去了

//第一种方法
        HashMap<String,Object> map = new HashMap<String, Object>();
        map.put("abc", 1);
        map.put("sada", "dddd");
        String[] keys = map.keySet().toArray(new String[]{});
        Object[] values = new Object[keys.length];
        for(int i=0;i<keys.length;i++){
            values[i] = map.get(keys[i]);
        }

        //第二种方法
        HashMap<String,Object> map = new HashMap<String, Object>();
        map.put("abc", 1);
        map.put("sada", "dddd");
        String[] keys = new String[map.size()];
        Object[] values = new String[map.size()];
        int i=0;
        for(Entry<String, Object> en:map.entrySet()){
            keys[i++] = en.getKey();
            values[i] = en.getValue();
        }


首先,将map中的key组成一个对象,借助JSON(fastjson)互相处理。如下

 @Test
    public void testMap() {
        List<Person> persons = new ArrayList<Person>();
        persons.add(new Person("name1"));
        persons.add(new Person("name2"));
        persons.add(new Person("name3"));
        toMap(persons);
    }

    private void toMap(List list) {
        String json = JSON.toJSONString(list);
        List<Map<String, Object>> map = JSON.parseObject(json, new TypeReference<List<Map<String, Object>>>() {
        });
        System.out.println(map);

        List<Person> persons = JSON.parseArray(JSON.toJSONString(map), Person.class);
        System.out.println(persons);
    }

    public static class Person {
        String name;

        public Person() {
        }

        public Person(String name) {
            this.name = name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }

如果“键”与“值”有相同的数据类型

转为数组的时候 奇数位置放置“键”,后面紧跟的偶数位置放置“值”
转map就不用说了吧

创建对象,将map里的键值对应放到对象里,把对象放到list里

map传array里,最好把key和value以"key,value"的形式存入array,再转回时只须split这个逗号,取出第1个和第2个值即是原key和value