1

After implementing the Hashmap I realized that it was not sorted alphabetically so now I wanted to know if there's another map that sorts the files for me? I tried using the code above but it says that I can't use sort in my listview type

 public ArrayList<HashMap<String, String>> songsList =
     new ArrayList<HashMap<String, String>>();

Collections.sort(songsList, new Comparator<String>() {
                        @Override
                        public int compare(String s1, String s2) {
                            return s1.compareToIgnoreCase(s2);
                        }
                    });
2
  • you can't use a Comparator<String> on HashMap, because HashMap is not String. (you need a Comparator<HashMap<String, String>>) Commented Jul 3, 2014 at 13:30
  • public List<Map<String, String>> songsList = new ArrayList<HashMap<String, String>>(); Commented Jul 4, 2014 at 10:46

2 Answers 2

2

EDIT -

You can just use the following -

    Collections.sort(songsList,new Comparator<HashMap<String,String>>(){
public int compare(HashMap<String,String> mapping1,
                    HashMap<String,String> mapping2){
    return mapping1.get("KEY").compareToIgnoreCase(mapping2.get("KEY"));
}

NOTE: Replace KEY with your key.

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

Comments

0

to store your data sorted you could also use the Sorted Map. then you should have no more problems with sorting the Map.

Greetings.

--- EDIT ---
SortedMap is an Interface, which is implemented by TreeMap. So if you want to use a custom Comparator you can easily implement SortedMap. As an minimal sample (with a treemap):

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

public static void main(final String[] args) {

    for(int i = 0; i < 5; i++){
        Map<String, String> map = new TreeMap<String, String>();
        map.put("A", "a");
        map.put("D", "d");
        map.put("B", "b");
        map.put("C", "c");
        list.add(map);
    }

    for (Map<String, String> map : list){
        for (String element : map.values()) {
            System.out.println(element);
        }
    }

}

To implement a SortedMap by yourself take a look at: this

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.