I am having trouble with this one part of my assignment: Create a Map where the key is a type of animal and the value is a list of CartoonCharacter objects that are that type of animal, stored in alphabetical order by name. Print each key from the map and the list of objects that key references. I understand how to create a map and what the keys and values represent but I am having trouble understanding how i would maybe iterate through the objects and extract the types to use as keys. maybe using the put method? here is code so far
public class CartoonDriver {
public static void main(String[] args) {
//Construct objects of cartoon characters
CartoonCharacter BugsBunny = new CartoonCharacter("Bugs Bunny","rabbit",1990);
CartoonCharacter RogerRabbit = new CartoonCharacter("Roger Rabbit", "rabbit",1858);
CartoonCharacter MickeyMouse = new CartoonCharacter("Mickey Mouse", "mouse",1928);
CartoonCharacter MinnieMouse = new CartoonCharacter("Minnie mouse", "mouse",1930);
CartoonCharacter RoadRunner = new CartoonCharacter("Road Runner", "roadrunner",1986);
CartoonCharacter DaffyDuck = new CartoonCharacter("Daffy Duck", "duck",1999);
CartoonCharacter DonaldDuck = new CartoonCharacter("Donald Duck", "duck",1958);
CartoonCharacter ScoobyDoo = new CartoonCharacter("Scooby Doo", "dog",1975);
CartoonCharacter WinnieThePooh = new CartoonCharacter("Winnie The Pooh", "bear",1963);
CartoonCharacter Snoopy = new CartoonCharacter("Snoopy", "dog",1959);
//Create toons array list to add characters to
List<CartoonCharacter> toons = new ArrayList<CartoonCharacter>();
//Add each characther to the array list
toons.add(BugsBunny);
toons.add(RogerRabbit);
toons.add(MickeyMouse);
toons.add(MinnieMouse);
toons.add(RoadRunner);
toons.add(DaffyDuck);
toons.add(DonaldDuck);
toons.add(ScoobyDoo);
toons.add(WinnieThePooh);
toons.add(Snoopy);
//print each object
for(CartoonCharacter toon : toons){
System.out.println(toon);
}
//Create Map to hold type of toon and toon object as value
Map<String, CartoonCharacter> toonsMap = new HashMap<>();
}
}
i have tired a couple things but they dont make since like using the put method as in toons.put(rabbit, BugsBunny); but that does not seem right to me to have to do that for every object
CartoonCharacterhas a means to get the type you could usetoons.put(toon.getType(), toon), but remember you can't have multiple keys, so you would need to use aListwhich contains theCartoonCharacterof the given type. You could then use aTreeMapwhich would order the keys. The point of usingtoon.getTypeis, you can just loop through your existingList;)