1

So I have an ArrayList with objects that have name, id, salary etc. And a Queues with another ArrayList objects, model, year etc. I created a HashMap and used the ArrayList objects as keys and the queues as values, associating each queue for a object in the arraylist.

The thing is, I have to list all the values for a determined key. I would like to know how can I return all the values of a hashmap depending on the name value of the object.

For example this my map:

{Mech [Name = Ella McCarthy , ID = 1]=[Car [model=Civic, year=2010, fix=flat tyres], Car [model=Audi A3, year=2012, fix=something broken]],

Mech [Name = Josh Reys , ID = 1]=[Car [model=Cruze, year=2014, fix=something broken], Car [model=Impala, year=1990, fix=something broken]]}

Is there any way of returning the value if the name in the object in the key equals to Ella McCarthy?

  • 1
    You need to override hashcode and equals. Does this answer your question? [Why do I need to override the equals and hashCode methods in Java?](https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java) – Christopher Schneider May 14 '20 at 16:56

1 Answers1

0

Next code may comprehensive for you:

public class MapExample {
private static final String DETERMINED_KEY = "Ella McCarthy";

Queue<Car> queue = new PriorityQueue<>();
Map<Mech, Queue<Car>> map = new HashMap<>();

Queue<Car> getValuesByNameInKeyObjectWithStreams() {
    Queue<Car> cars = map.entrySet()
            .stream()
            .filter(mapEntry -> mapEntry.getKey().getName().contentEquals(DETERMINED_KEY))
            .map(Map.Entry::getValue)
            .findFirst()
            .orElseThrow(); // Throw exception if did't find according value. Or return another result with orElse(result)

    return cars;
}

Queue<Car> getValuesByNameInKeyObjectBeforeJava8() {
    for (Map.Entry<Mech, Queue<Car>> entry : map.entrySet()) {
        String mechName = entry.getKey().getName();

        if (mechName.equals(DETERMINED_KEY)) {
            return entry.getValue();
        }
    }

    // Throw exception or return another result
    throw new  RuntimeException("If didn't find exception");
}

}

class Mech {
String name;

public String getName() {
    return name;
}

}

class Car {
String value;

}

If you prefer functional style and use java 8 or higher, peek getValuesByNameInKeyObjectWithStreams method.