假设我有一个Map< String,String>我想删除所有包含foo的值.在优化/内存等方面,最好的方法是什么?下面的四个syso打印相同的结果,也就是说{n2 = bar}.
public static void main(String[] args) {
Map in = new HashMap();
in.put("n1","foo");
in.put("n2","bar");
in.put("n3","foobar");
// 1- create a new object with the returned Map
Map in1 = new HashMap(in);
Map out1 = methodThatReturns(in1);
System.out.println(out1);
// 2- overwrite the initial Map with the returned one
Map in2 = new HashMap(in);
in2 = methodThatReturns(in2);
System.out.println(in2);
// 3- use the clear/putAll methods
Map in3 = new HashMap(in);
methodThatClearsAndReadds(in3);
System.out.println(in3);
// 4- use an iterator to remove elements
Map in4 = new HashMap(in);
methodThatRemoves(in4);
System.out.println(in4);
}
public static Map methodThatReturns(Map in) {
Map out = new HashMap();
for(Entry entry : in.entrySet()) {
if(!entry.getValue().contains("foo")) {
out.put(entry.getKey(),entry.getValue());
}
}
return out;
}
public static void methodThatClearsAndReadds(Map
}
}
in.clear();
in.putAll(out);
}
public static void methodThatRemoves(Map in) {
for(Iterator> it = in.entrySet().iterator(); it.hasNext();) {
if(it.next().getValue().contains("foo")) {
it.remove();
}
}
}