实现
{ "a": [ 1, 2, 3 ], "b": [ 3, 7 ] }
当然, HashMap<String, List<Integer>> 是可以的,但是不方便。这里使用Multimap
举例
package com.example.ch6_2; import java.util.Collections; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; public class testMultimap { public static void main(String[] argv) { Multimap<String, String> myMultiMap = ArrayListMultimap.create(); myMultiMap.put("Fruits", "Apple"); myMultiMap.put("Fruits", "Pear"); myMultiMap.put("Fruits", "Banana"); myMultiMap.put("Vegetables", "eggplant"); System.out.println(" myMultiMap size:" + myMultiMap.size()); System.out.println(" myMultiMap.get(Fruits): " + myMultiMap.get("Fruits")); System.out.println(" myMultiMap.get(Vegetables): " + myMultiMap.get("Vegetables")); System.out.println(" keys:"); for (String key : myMultiMap.keys()) { System.out.println(key); } System.out.println(" values:"); for (String value : myMultiMap.values()) { System.out.println(value); } myMultiMap.remove("Fruits", "Apple"); System.out.println(" myMultiMap size:" + myMultiMap.size()); myMultiMap.removeAll("Fruits"); System.out.println(" myMultiMap size:" + myMultiMap.size()); } }
结果
myMultiMap size:4 myMultiMap.get(Fruits): [Apple, Pear, Banana] myMultiMap.get(Vegetables): [eggplant] keys: Vegetables Fruits Fruits Fruits values: eggplant Apple Pear Banana myMultiMap size:3 myMultiMap size:1