I really need to solve a problem i’ve been stuck into for 3 days. Any help would be appreciated.
I have a Car class with brand, model and color instance variables.
I have a Preferences class with name, brand, model and color instance variables.
I have a preferences (Key = name, value = Car) HashMap that contains people’s names as keys and Car they would like to drive as values.
Finally i have a names ArrayList that contains all the names in the system.
I want somehow to group the names of the people according to the car they would like to drive.
For example i want the output to be something like:
Ford Focus, 2006, Blue : Nick,Bill,Jim
Opel Astra, 2008, Black : Joe, George
Mercedes CLK, 2009, Black : Steve, Chris, John
The first thing i thought of was, that i could hold all the duplicates in a list and then get the names of that list, but i figured out i can’t form groups of people according to their preferred car. So, i think the following piece of code doesn’t help at all.
Preferences[] p = new Preferences[preferences.size()];
for (int i = 0; i < preferences.size(); i++) {
p[i] = (Preferences) preferences.get(names.get(i));
Car car = new Car(p[i].getBrand(), p[i].getModel(), p[i].getColor());
if (!set.add(car)) { //duplicate
System.out.println("Duplicate!");
listOfDuplicates.add(car);
}
}
Is there anything i can do?
Here you go…
It would be even easier with Guava’s Multimap.