0

i want sort this Map:

Map<String, Collection<String[]>> map = new HashMap<String, Collection<String[]>>();

In map is for example:

String key = "MyKey";
Collection<String[]> values = new ArrayList<String[]>();
map.put(key, values);

String[] firstValues = { "John", "21", "M"};
values.add(firstValues); //Name, Age, Gender

String[] secondValues = { "Jane", "31", "W"};
values.add(secondValues);

etc.

so finnaly, i have: map with:

Mykey : [["John", "21", "M"], ["Eve", "31", "W"]];

And i want do:

Collection<String[]> values = map.get(key);

and then sort by specific index, for example by first index(name) alphabetically, or by second index(age). So after first sort will be:

Mykey : [["Eve", "31", "W"], ["John", "21", "M"]];

after second sort:

Mykey : [["John", "21", "M"], ["Eve", "31", "W"]];
1
  • 2
    A Collection is not necessarily ordered. You might want to use List instead. Commented Jul 28, 2012 at 20:47

2 Answers 2

5

Your code looks to me like something a developer experienced in dynamic languages such as Ruby would write. You'll probably find out that this is not your best avenue with Java. You should model your String[] with an appropriate object containing those strings as properties.

Also I think that the map part of your question is not very relevant—you are in effect dealing with a collection of objects that you need to sort by one of the properties. That you happen to have several such collections in a map doesn't influence the solution.

The sorting itself is done as @Havard Geithus has already advised you.

Sign up to request clarification or add additional context in comments.

Comments

3

Use the API java.util.Collections.sort(List list, Comparator c) which specifies a comparator, and implement it as you wish (one for name, and another one for age)

Also, instead of using String[]{name, age, gender} as elements, create a class Person having these variables as members. I would probably place the two comparators you want inside this class as well:

public static final Comparator<Person> AGE_COMPARATOR = new Comparator<Person>() {
    @Override
    public int compare(Person p1, Person p2) {
        // implement
    }
};

Now you could simply call

Collections.sort(map.get(key), Person.AGE_COMPARATOR);

Assuming you used the List interface instead of the Collection interface as @Vatev suggested:

Map<String, List<Person>> map = new HashMap<String, List<Person>>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.