I have a Hashmap< String, String> p and I’m trying to replace half of the values of the keys with ‘-‘
For instance, lets say my current Hashmap has the following values
"A", "100"
"B", "400"
"C", "600"
"D", "845"
I want to somehow manipulate only half (first two in this case) of the key of the values by changing their values from the provided integer to a ‘-‘.
So it would look like this:
"A", "-"
"B", "-"
"C", "600"
"D", "845"
I’ve attempted this, but to no avail.
for (String i : p.keySet()/2) {
p.replace(i, '-')
}
Is there a way to do this? If yes, can you please explain how?
>Solution :
You should do something like this:
int maxiterations = p.keySet().size() / 2;
Iterator<String> iterator = p.keySet().iterator();
for (int i=0; i < maxiterations; i++) {
if (iterator.hasNext()) {
String key = iterator.next();
p.replace(key, "-");
}
}
Or
int iterations = p.keySet().size() / 2;
do {
if (iterator.hasNext()) {
p.replace(iterator.next(), "-");
}
} while (--iterations > 0);