Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is is possible to iterate through only half of the provided hashmap?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading