Rahul Koshaley Rahul Koshaley - 4 months ago 28
Java Question

Selecting a RANDOM key and then breaking out of Iterator / loop in HashMap

I'm trying to loop through a HashMap such that it should select any random KEY and if that KEY is found it should break out of the loop and select the value corresponding to that KEY.

But somehow this code is not working and it is selecting only a particular value. Please note that it has all the values and keys for which I have coded the IF statement below.

Below is my code

Iterator<Entry<String, Set<String>>> it = arg0.getSubstylearea().entrySet().iterator();

A: while (it.hasNext()) {
Map.Entry<String, Set<String>> entry = (Map.Entry<String, Set<String>>) it.next();
String key = entry.getKey();
Set<String> temp = arg0.getSubstylearea().get(key);

if (key.equals("Eyes")) {
flatont.setStylearea1(key);
System.out.println("This Doesnt Print");
for (String s : temp) {

flatont.setStylesubarea1(s);

}
break A;
} else if (key.equals("Face")) {

flatont.setStylearea1(key);

for (String s : temp) {

flatont.setStylesubarea1(s);
}
break A;
} else if (key.equals("Lips")) {

flatont.setStylearea1(key);

for (String s : temp) {

flatont.setStylesubarea1(s);
}
break A;
}
}


Please help me with how to achieve this

Answer

I'm not entirely sure I understand what you're after, but try this:

    Map<String, Set<String>> map = arg0.getSubstylearea()
    int index = new Random().nextInt(map.size());
    int i = 0;
    for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
        if (i++ < index) {
            continue;
        }
        String key = entry.getKey();
        Set<String> temp = arg0.getSubstylearea().get(key);

        if (key.equals("Eyes")) {
            flatont.setStylearea1(key);
            System.out.println("This Doesnt Print");
            for (String s : temp) {

                flatont.setStylesubarea1(s);

            }
        } else if (key.equals("Face")) {

            flatont.setStylearea1(key);

            for (String s : temp) {

                flatont.setStylesubarea1(s);
            }
        } else if (key.equals("Lips")) {

            flatont.setStylearea1(key);

            for (String s : temp) {

                flatont.setStylesubarea1(s);
            }
        } else {
            // Do something else
        }
        break;
    }