我有一个HashMap,用于存储整数ID和字符串值。
我希望能够基于用户输入的String从HashMap中删除内容。我一直这样做的方式如下:
public void pickingVehicleUp() {
System.out.println("Please enter number plate: ");
input = new Scanner(System.in);
String PLATE = input.nextLine();
Iterator<Map.Entry<Integer, String>> iter = zone_1.entrySet().iterator();
Map.Entry<Integer, String> Empty1 = iter.next();
Map.Entry<Integer, String> Empty2 = iter.next();
Map.Entry<Integer, String> Empty3 = iter.next();
Map.Entry<Integer, String> Empty4 = iter.next();
Map.Entry<Integer, String> Empty5 = iter.next();
zone_1.entrySet().removeIf(entry -> (PLATE.equals(entry.getValue())));
if (Empty1.getValue().equals(PLATE)) {
Integer key = Empty1.getKey();
zone_1.put(key, "Empty");
} else if (Empty2.getValue().equals(PLATE)) {
Integer key = Empty2.getKey();
zone_1.put(key, "Empty");
} else if (Empty3.getValue().equals(PLATE)) {
Integer key = Empty3.getKey();
zone_1.put(key, "Empty");
} else if (Empty4.getValue().equals(PLATE)) {
Integer key = Empty4.getKey();
zone_1.put(key, "Empty");
} else if (Empty5.getValue().equals(PLATE)) {
Integer key = Empty5.getKey();
zone_1.put(key, "Empty");
} else {
System.out.println("That number plate doesn't exist!");
}
}
虽然此代码可以正常工作,但我认为它很不整洁,并且可能有更有效的方法来实现,并且我想找到其中一种方法,因为我需要对5个不同的HashMap执行相同的方法
答案 0 :(得分:0)
也许这样可以帮助您
String PLATE = "PLATE";
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "DOOR");
map.put(2, "DOG");
map.put(3, "PLATE");
map.put(4, "SNOW");
System.out.println("Before check - " + map);
if (map.containsValue(PLATE)) {
for (Map.Entry<Integer, String> item:map.entrySet()) {
if (item.getValue().equals(PLATE)) {
map.remove(item.getKey());
break;
}
}
}
System.out.println("After check - " + map);
答案 1 :(得分:0)
如果您按照JB Nizet在评论中建议的那样反转地图,可能会更容易。直观地,如果您要查找车牌及其位置,则对于您的地图而言,存储停车位ID作为车牌号的函数更为有意义。然后它使您的任务变得微不足道:
Devices
但是,如果您保持将停车位映射到许可位置的最新设计,我们可以执行以下操作:
String PLATE = "PLATE1";
Map<String, Integer> plateToParkingSpaceID = new HashMap<>();
plateToParkingSpaceID.put("PLATE1", 1);
plateToParkingSpaceID.put("PLATE2", 2);
plateToParkingSpaceID.put("PLATE3", 3);
plateToParkingSpaceID.put("PLATE4", 4);
if (plateToParkingSpaceID.containsKey(PLATE)) {
plateToParkingSpaceID.remove(PLATE);
} else {
System.out.println("That number plate doesn't exist!");
}