In Java, you can usually remove items or entries with some specific value from Map or HashMap object using traditional method:
public Map<String, String> removeItemByValue(Map<String, String> data, String value) {
for (var key: data.keySet()) {
if (data.get(key) == null) {
data.remove(key);
}
}
return data;
}
var data = new HashMap<String, String>();
data.put("a", "1");
data.put("b", "2");
data.put("c", "2");
removeItemByValue(data, null);
// only prints a = 1
for (var key: data.keySet()) {
System.out.println(key + "=" + data.get(key));
}
A Better Map-Item Removal Approach via using values()
The values() method in Map object actually returns a Collection view of the valujes that are contained in the map object. And the remove object return null when the item is not existent anymore. Thefore, we can use the following modern 1-liner in Java to remove the items in a Map that have the specific value.
public Map<String, String> removeItemByValue(Map<String, String> data, String value) {
while (data.values().remove(value)) ;
return data;
}
To double check and verify that items are actually removed:
package com.helloacm;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
var data = new HashMap<String, String>();
data.put("a", "b");
data.put("e", "2");
data.put("f", "2");
while (data.values().remove("2"));
// prints "a"
for (Map.Entry<String, String> entry: data.entrySet()) {
System.out.println(entry.getKey());
}
}
}
--EOF (The Ultimate Computing & Technology Blog) --
Reposted to Blog
Every little helps! I hope this helps!
Steem On!~
If you like my work, please consider voting for me or Buy Me a Coffee, thanks!
https://steemit.com/~witnesses type in justyy and click VOTE
Alternatively, you could proxy to me if you are too lazy to vote!
Also: you can vote me at the tool I made: https://steemyy.com/witness-voting/?witness=justyy
拍拍拍
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
感谢,回赞。
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
支持行长👏
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
代理给你时报错:
Oops, something went wrong. Here is the error message:
"account.proxy != o.proxy: Proxy must change."
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
你已经设置我为见证人代理了
如果你是指 SP 代理,请用这个:
https://steemyy.com/delegate-form/?delegator=chaimyu&delegatee=justyy
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
对,全代理给你吧
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
感谢。
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit