-6

Problem: Write a method called personIndex() where you pass in an ArrayList of person objects. Place each person object with its corresponding id number in HashMap. Return a collection of the person objects in order.

Could someone explain / show how I would do this?

This is my code:

public Collection<person> personIndex(ArrayList<Person> parameterArr)
{
    HashMap<String, Person> answerMap = new HashMap<String, Person>();

    for (Person p: parameterArr)
    {
        answerMap.put(p.getID(), p)
    }
     return answerMap.values();
}

Question: Is my code correct? Will it return a collection?

I want to know if this is a syntactically correct way to return a collection, and also how would you write this method?

PROBLEM:
when you write the method nothing is being returned but the compiler says everything is syntactically correct

Thank you!

1 Answers1

0

It seems you don't have any problem in the method you have shown other than not capitalizing "person" in your method return type to represent the Person class.

After the enhanced-for loop is finished you have a result of a hashmap with the keys being the person IDs of type String and the values being the Person objects. If you want to return the hashmap with its keys in order (1... 2... 3... 4), you can see this question how to sort Map values by key in Java. Since String already implements the Comparable interface various methods in the question I linked will have a pre-defined sorting method (from the String class) to sort the strings.

After sorting the hashmap you can get the values as a collection and return that, since now it will be sorted depending on the IDs.

In the future please show your attempt at ordering the keys in the hashmap.

Community
  • 1
  • 1
Mario Ishac
  • 5,060
  • 3
  • 21
  • 52