连接两个 HashMap 值
Connect two HashMap Values
我有这个 JSON 字符串:
String json = "{\"countries\":{\"2\":\"China\",\"3\":\"Russia \",\"4\":\"USA\"},\"capitals\":{\"2\":Beijing,\"4\":null,\"3\":Moscow}}";
我使用这个将字符串转换为 HashMap:
HashMap<String,Object> map = new Gson().fromJson(json, new TypeToken<HashMap<String, Object>>(){}.getType());
System.out.println(map.get("countries")+"@@@@@"+map.get("capitals"));
现在我的输出是:
{2=China, 3=Russia , 4=USA}@@@@@{2=Beijing, 4=null, 3=Moscow}
我想用数字连接这些值。我想像这样创建两个 ArrayList:
A)- [中国、俄罗斯、美国]
B)- [北京,莫斯科,null]
我该怎么做?
首先,您需要将 map.get("label")
转换为 LinkedTreeMap<Integer, String>
,然后用它的值创建新的 ArrayList
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);
您可以遍历国家/地区键集以填充大写数组:
List<String> countries = new ArrayList<>(countriesMap.values());
List<String> capitals = new ArrayList<>();
for (String countryKey : countriesMap.keySet()) {
capitals.add(capitalsMap.get(countryKey));
}
我有这个 JSON 字符串:
String json = "{\"countries\":{\"2\":\"China\",\"3\":\"Russia \",\"4\":\"USA\"},\"capitals\":{\"2\":Beijing,\"4\":null,\"3\":Moscow}}";
我使用这个将字符串转换为 HashMap:
HashMap<String,Object> map = new Gson().fromJson(json, new TypeToken<HashMap<String, Object>>(){}.getType());
System.out.println(map.get("countries")+"@@@@@"+map.get("capitals"));
现在我的输出是:
{2=China, 3=Russia , 4=USA}@@@@@{2=Beijing, 4=null, 3=Moscow}
我想用数字连接这些值。我想像这样创建两个 ArrayList:
A)- [中国、俄罗斯、美国]
B)- [北京,莫斯科,null]
我该怎么做?
首先,您需要将 map.get("label")
转换为 LinkedTreeMap<Integer, String>
,然后用它的值创建新的 ArrayList
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);
您可以遍历国家/地区键集以填充大写数组:
List<String> countries = new ArrayList<>(countriesMap.values());
List<String> capitals = new ArrayList<>();
for (String countryKey : countriesMap.keySet()) {
capitals.add(capitalsMap.get(countryKey));
}