mercredi 1 mai 2019

Iterating through a HashMap until the first value is found?

I have a HashMap that I have used to store an integer id and an String value.

I wanted to be able to remove things from the HashMap based off of a user input String. The way I have been doing that is as followed:

        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!");
        }
    }

While this code works fine, I think that it is very untidy and there are probably much more efficient ways to do it and i'd like to find one of those ways as I need to do this same method for 5 different HashMaps.

Aucun commentaire:

Enregistrer un commentaire