0

Looking for a solution using Java version 7 and below.

I have the following list of maps.

List<Map.Entry<String, Person>> stuff = new ArrayList<>();

This is Person class

class Person{
    private String name;
    private int order;

    // get set
}

I want to sort the list "stuff" based on Person's order. How can I do this? I was planning on implementing Comparable on the Person class and write the logic for comparison.

But how do I sort it since the Person object is held as a value in a map which in turn is held in a list. For me to sort a Map, I was thinking maybe I could consider a TreeMap. Then again I am not sure if I am over complicating things.

I need to keep that structure of a List holding a Map of keys as Strings and values as Person. Appreciate any input on this. Thanks.

kang
  • 707
  • 4
  • 17

1 Answers1

9

Just create a Comparator that compares the desired fields:

Collections.sort(stuff, new Comparator<Map.Entry<String, Person>>() {
    @Override
    public int compare(Map.Entry<String, Person> entry1, Map.Entry<String, Person> entry2) {
        return Integer.compare(entry1.getValue().getOrder(), entry2.getValue().getOrder());
    }
});

Once you're on Java 8, this becomes much easier:

stuff.sort(Comparator.comparingInt(e -> e.getValue().getOrder()));
shmosel
  • 49,289
  • 6
  • 73
  • 138