Reputation: 129
I have got these values in my HashMap
,
"ver":"a"
"ver":"b"
"ver":"c"
"os":"d"
"os":"e"
i need only:
"os":"d"
"os":"e"
My code is:
String[] eachPair = myString.split(",");
Map<String,String> pairs = new HashMap<String,String>();
for(String pair: eachPair) {
pairs.put(pair.substring(0, pair.indexOf(":")).trim(), pair.substring(pair.indexOf(":")+1));
}
pairs.get("os");
but its not working. please help
Upvotes: 0
Views: 64
Reputation: 8473
HahMap
doesn't allows duplicate keys.So I recommand to use Guava's MultiMap
or apache's MultiValueMap
Please look into
the sample code reference of MultiMap: http://tomjefferys.blogspot.in/2011/09/multimaps-google-guava.html
the sample code reference of MultiValueMap: http://java.dzone.com/articles/allowing-duplicate-keys-java
Upvotes: 1
Reputation: 1940
Map
should have unique keys only, If you add a value with the same key which is already exist in the map, value for that key will be override and you will lost the old value.
Upvotes: 1
Reputation: 26094
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
Upvotes: 1