Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort <Integer, MyObject> map

I have map like that:

Map<Integer, MyEntry> map = new HashMap<Integer, MyEntry>();

MyEntry is that:

public class MyEntry {
    private String title;
    private String value;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
}

after putting values in map , I want to sort it. First element to be smallest and the last element to be biggest.

like image 730
grep Avatar asked Aug 25 '13 17:08

grep


1 Answers

For sorting by key, you can use a SortedMap - one common implementation is a TreeMap. Since Integers have a natural sort order, you don't need to do anything special other than just put them into a TreeMap

If you wanted to sort by values, there are a couple of techniques described in this question Sort a Map<Key, Value> by values (Java)

like image 96
Jeff Storey Avatar answered Oct 08 '22 23:10

Jeff Storey