Skip to content

Connect two HashMap Values

I’ve got this JSON string:

String json = "{"countries":{"2":"China","3":"Russia ","4":"USA"},"capitals":{"2":Beijing,"4":null,"3":Moscow}}"; I converted string to HashMap, using this:

   HashMap<String,Object> map = new Gson().fromJson(json, new TypeToken<HashMap<String, Object>>(){}.getType());

And now my output is:

{2=China, 3=Russia , 4=USA}@@@@@{2=Beijing, 4=null, 3=Moscow}

I would like to connect this values by numbers. I want to create two ArrayList like this:

A)- [China,Russia,USA]

B)- [Beijing,Moscow,null]

How can i do it?


First, you need to cast map.get("label") to LinkedTreeMap<Integer, String>, then create new ArrayList with it’s values

        String json = "{"countries":{"2":"China","3":"Russia ","4":"USA"},"capitals":{"2":Beijing,"4":null,"3":Moscow}}";
        HashMap<String,TreeMap<Integer, String>> map = new Gson().fromJson(json, new TypeToken<HashMap<String, TreeMap<Integer, String>>>(){}.getType());
        ArrayList<String> countries = new ArrayList<>(map.get("countries").values());

        ArrayList<String> capitals = new ArrayList<>(map.get("capitals").values());