Nick
Nick

Reputation: 3494

Sort TreeMap based on values?

I have a TreeMap that holds the following keys/values:

    private ArrayList<TreeMap<String,String>> mList = new ArrayList<TreeMap<String,String>>();
    TreeMap<String,String> item = new TreeMap<String,String>();
    item.put("FirstName", strFirstName);  
    item.put("LastName", strLastName);
    item.put("Country", strCountry);
    mList.add( item );

How can I sort the TreeMap by the values stored under the "LastName" key after adding all the items? I would like to have a TreeMap in the same format as the original list but with the mentioned sorting applied:

"James", "Amish", "USA"
"Charles", "Brentwood", "USA"
"Jake", "Cornell", "USA"
"Amy", "Dunn", "USA"
"Melinda", "Ellis", "Canada"

I've found a similar question relating to sorting a TreeMap by values in 'regular' Java, but the code didn't work for me - I don't know if because of Android pecularities or my inability to adapt it to fit my needs :-/

Thanks,
Nick

Upvotes: 1

Views: 1067

Answers (3)

Nicholas
Nicholas

Reputation: 7501

It would be wrong to sort a TreeMap by values when the keys are what are compared. If you want a List that is sorted use TreeSet rather then TreeMap.

Upvotes: 0

Oscar Gomez
Oscar Gomez

Reputation: 18488

I have not programmed for android, but I do not think there are any diferences. A TreeMap is always sorted, in fact if it cannot sort something it will throw an exception. Anyway since you are using String they will be sorted by natural order, which is really just a fancy word for the actual implementation of Comparable on the String class, which just sorts alphabetically.

If you want it to sort it in any other way, there is a constructor of TreeMap that receives a Comparator, in which there is only one method to implement which is compare, here you can specify the desired sorting.

Hope that helps.

Upvotes: 0

nerdytenor
nerdytenor

Reputation: 431

It sounds like you are trying to sort the ArrayList containing the TreeMaps, correct? If so, the following should suit your needs:

Collections.sort(mList, new Comparator<TreeMap<String, String>>(){
    public int compare(TreeMap<String, String> left, TreeMap<String, String> right) {
        return left.get("LastName").compareTo(right.get("LastName"));
    }
});

It should be noted that the use of a TreeMap to contain a list of name/value pairs is probably not necessary - I would just create a class to hold the values.

Upvotes: 4

Related Questions