Question

I have an ArrayList defined as so:

ArrayList<HashMap<String, String>> recallList = new ArrayList<HashMap<String, String>>();

Each map only has one element in it company which is the name of a company. My question is how do I alphabetize the ArrayList. I am using this because later down the line (in other views) there will be more elements to the HashMap.

Was it helpful?

Solution

Use the following:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

public class MainClass {
  public static void main(String[] args) {
    ArrayList<HashMap<String, String>> recallList = new ArrayList<HashMap<String, String>>();
    HashMap<String, String> hashMap;
    hashMap = new HashMap<String, String>();
    hashMap.put("company", "a");
    recallList.add(hashMap);
    hashMap = new HashMap<String, String>();
    hashMap.put("company", "c");
    recallList.add(hashMap);
    hashMap = new HashMap<String, String>();
    hashMap.put("company", "b");
    recallList.add(hashMap);
    System.out.println(recallList);
    Collections.sort(recallList, new Comparator<HashMap<String, String>>() {
      @Override
      public int compare(HashMap<String, String> hashMap1, HashMap<String, String> hashMap2) {
        return hashMap1.get("company").compareTo(hashMap2.get("company"));
      }
    });
    System.out.println(recallList);
  }
}

The first and second output are:

[{company=a}, {company=c}, {company=b}]
[{company=a}, {company=b}, {company=c}]

OTHER TIPS

You can use Collections.sort() to sort it in lexicographically order but you have make the object comparable by using Comparator

class CmpHashMap implements Comparator<HashMap<String,String>>
{
    public int compare(HashMap<String,String> h1,HashMap<String,String> h2)//assuming second String as company name and key as "key"
    {
         return h1.get("key").compareTo(h2.get("key"));
     }
 }

then use collections

Collections.sort(recalllist,new CmpHashMap());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top