Skip to content
Advertisement

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());
   System.out.println(map.get("countries")+"@@@@@"+map.get("capitals"));

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?

Advertisement

Answer

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());
        System.out.println(countries);

        ArrayList<String> capitals = new ArrayList<>(map.get("capitals").values());
        System.out.println(capitals);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement