Java – HashMap that maintains the original key / value when entering duplicate keys
•
Java
Can HashMap retain its original key / value pair when entering duplicate keys?
For example, suppose I have something like this:
Map<String,String> map = new HashMap<String,String>(); map.put("username","password1"); map.put("username","password2");
I want the original key / value pair - username and password 1 to be reserved and not overwritten by username and password 2
Is that possible? If not, how can I eliminate duplicate entries and put them into the map?
Solution
As mentioned earlier, if you use Java 8, you can use putifabsent
If you are using an older java version, you can use concurrenthashmap, which has the putifabsent method
Of course, you get the extra overhead of thread safety, but you shouldn't worry if you don't write extremely performance - sensitive applications
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
二维码