विधि में संशोधित करें मान लें कि मुझे Map<String, String>
मिला है और मैं foo
वाले सभी प्रविष्टियों को हटाना चाहता हूं। अनुकूलन/स्मृति/आदि के संदर्भ में ऐसा करने का सबसे अच्छा तरीका क्या है? नीचे दिए गए चार syso
एक ही परिणाम प्रिंट कर रहे हैं, जो {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);
System.out.println(out1);
// 2- overwrite the initial Map with the returned one
Map<String, String> in2 = new HashMap<String, String>(in);
in2 = methodThatReturns(in2);
System.out.println(in2);
// 3- use the clear/putAll methods
Map<String, String> in3 = new HashMap<String, String>(in);
methodThatClearsAndReadds(in3);
System.out.println(in3);
// 4- use an iterator to remove elements
Map<String, String> in4 = new HashMap<String, String>(in);
methodThatRemoves(in4);
System.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, 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());
}
}
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();
}
}
}
यह बिल्कुल सही नहीं है कि क्या तरीका है? – tibtof
हाँ यह बराबर से अलग कैसे है, जो वह वैसे भी नहीं चाहता है – jonasr
ओह! मैंने सवाल स्किम किया:/मैं कोड हटा दूंगा :) – Bohemian