Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

java - sorting a List of Map<String, String>

I have a list variable created like this:

List<Map<String, String>> list = new ArrayList<Map<String, String>>();

In my Android application, this list gets populated.

just an example:

Map<String, String> map1 = new HashMap<String, String>();
map.put("name", "Josh");
...

Map<String, String> map2 = new HashMap<String, String>();
map.put("name", "Anna");
...

Map<String, String> map3 = new HashMap<String, String>();
map.put("name", "Bernie");
...

list.add(map1);
list.add(map2);
list.add(map3);

I am using list to show results in a ListView by extending BaseAdapter and implementing the various methods.

My problem: I need to sort list in alphabetical order based on the map's key name

Question: What is a simple way to sort list in alphabetical order based on the map's key name?

I can't seem to wrap my head around this. I have extracted each name from each Map into a String array, and sorted it(Arrays.sort(strArray);). But that doesn't preserve the other data in each Map, so i'm not too sure how i can preserve the other mapped values

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following code works perfectly

public Comparator<Map<String, String>> mapComparator = new Comparator<Map<String, String>>() {
    public int compare(Map<String, String> m1, Map<String, String> m2) {
        return m1.get("name").compareTo(m2.get("name"));
    }
}

Collections.sort(list, mapComparator);

But your maps should probably be instances of a specific class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...