how to return objects from hashmap

Car c1 = new Car();
Car c2 = new Car();

HashMap<String,Car> hm= new HashMap<String, Car>();
hm.put("Ford",c1);
hm.put("Volvo",c2);

How do I iterate to get only the values(only name) to be printed?

Out should be:
c1
c2

Not the below :
[email protected]
[email protected]

Answer

Step 1: First you have to override the toString() method in the Car class.

public class Car {
    // attribute
    private final String name;

    // Constructor
    public Car(final String name) {
        this.name = name;
    }

    // getter
    public String getName() {
        return name;
    }

    // Override of toString
    @Override
    public String toString() {
        return name;
    }
}

If you don’t implement a proper toString-method the method from Object will be used when you invoke System.out.println(car), and that implementation returns the following (which is what you see in your current printing):

return getClass().getName() + "@" + Integer.toHexString(hashCode());

The way you create a new Car from the class above is to invoke the following constructor:

Car c = new Car("Ford");

Step 2: iterate using a loop. When using a Map you can choose to iterate over the keys, the values or the entries. All of these three alternatives returns some kind of Collection. Collections can be iterated using various types of loops.

// Standard Java 5+ foreach-loop that prints the values
for (Car c : hm.values()) {
    System.out.println(c);
}

// Loop using an iterator that prints the keys
for (Iterator<Car> itr = hm.keys().iterator(); itr.hasNext(); ) {
    System.out.println(itr.next());
}

// Or a Java 8 loop
hm.values().forEach(System.out::println);

If you instead want the keys of the map (“Ford”, “Volvo”) you can replace the call to values() with a call to keySet(). For the entries, invoke the method entrySet() which returns a Map.Entry object where you can get both the key (via getKey() and the value via getValue()).

Leave a Reply

Your email address will not be published. Required fields are marked *