Java – pass the object as a parameter and modify it within the method
•
Java
Suppose I have a map < string, string > I want to delete all the values containing foo What is the best way to optimize / memory? The following four sysos print the same result, that is, {N2 = bar}
public static void main(String[] args) {
Map<String,String> in = new HashMap<String,String>();
in.put("n1","foo");
in.put("n2","bar");
in.put("n3","foobar");
// 1- create a new object with the returned Map
Map<String,String> in1 = new HashMap<String,String>(in);
Map<String,String> out1 = methodThatReturns(in1);
Sy@R_301_2354@.out.println(out1);
// 2- overwrite the initial Map with the returned one
Map<String,String> in2 = new HashMap<String,String>(in);
in2 = methodThatReturns(in2);
Sy@R_301_2354@.out.println(in2);
// 3- use the clear/putAll methods
Map<String,String> in3 = new HashMap<String,String>(in);
methodThatClearsAndReadds(in3);
Sy@R_301_2354@.out.println(in3);
// 4- use an iterator to remove elements
Map<String,String> in4 = new HashMap<String,String>(in);
methodThatRemoves(in4);
Sy@R_301_2354@.out.println(in4);
}
public static Map<String,String> methodThatReturns(Map<String,String> in) {
Map<String,String> out = new HashMap<String,String>();
for(Entry<String,String> entry : in.entrySet()) {
if(!entry.getValue().contains("foo")) {
out.put(entry.getKey(),entry.getValue());
}
}
return out;
}
public static void methodThatClearsAndReadds(Map<String,entry.getValue());
}
}
in.clear();
in.putAll(out);
}
public static void methodThatRemoves(Map<String,String> in) {
for(Iterator<Entry<String,String>> it = in.entrySet().iterator(); it.hasNext();) {
if(it.next().getValue().contains("foo")) {
it.remove();
}
}
}
Solution
The best method is methodthatremoves because:
>In terms of memory consumption: it will not create a new map, so it will not increase memory overhead. > In terms of CPU usage: iterator has o (1) complexity, which is used to call next or delete the current element
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
