迭代HashMap并得到"最低" Object中值的整数

时间:2012-09-21 22:31:52

标签: java object hashmap iteration

    for (Entry<String, Data> entry : list.entrySet()) {
        if(entry.getValue().getRoom() == 1){
            if(entry.getValue().getName().equalsIgnoreCase("RED")){
                 entry.getValue().getPosition() // need to get the lowest free number
                 // between the range of 1-6
            } 
        }
    }

如何在这种情况下获得getPosition的最低免费点。 getPosition值介于1-6之间,每个值Room = 1和Name = RED中只有一个。 例如,如果getPosition中存在1,3,4,6(其中room = 1且name = red)则输出应为2.这是特定组合中getPosition中可用的最小数字。希望你能帮助我。

1 个答案:

答案 0 :(得分:4)

嗯,听起来像最简单的方法会是这样的:

boolean[] taken = new boolean[7]; //(0-6 inclusive)
// You were never using the key as far as I could see...
for (Data data : list.values()) {
   if (data.getRoom() == 1 && data.getName().equalsIgnoreCase("RED")) {
       taken[data.getPosition()] = true;
   }
}

for (int i = 1; i <= 6; i++) {
    if (!taken[i]) {
        return i;
    }
}

// Do whatever you want if there are no free positions...