使用hashMap对数据操作。
public class Test {
static HashMap<String, Set<String>> hashMap = new HashMap<>();
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("北京");
hashMap.put("city", set);
if(hashMap.containsKey("city")) {
hashMap.get("city").add("苏州");
} else {
Set<String> set = new HashSet<>();
setTmp.add("上海");
hashMap.put("city", set);
}
System.out.println(hashMap.toString());
}
}
优化之后的写法:
public class TestComputeIfAbsent {
static HashMap<String, Set<String>> hashMap = new HashMap<>();
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("北京");
hashMap.put("city", set);
hashMap.computeIfAbsent("city", key -> getValues(key)).add("苏州");
System.out.println(hashMap.toString());
}
public static HashSet getValues(String key) {
return new HashSet();
}
}