-2

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.

heinst
  • 8,520
  • 7
  • 41
  • 77
  • 4
    You can use `Collections.sort()` with a custom comparator. You can find [many examples on stackoverflow](http://stackoverflow.com/search?q=[java]%20collections%20sort%20comparator), for example: http://stackoverflow.com/questions/14154127/collections-sortlistt-comparator-super-t-method-example – assylias Feb 22 '14 at 22:27
  • Please expand on this in the answers section. Im still a bit confused. – heinst Feb 22 '14 at 22:28
  • Please define "alphabetize". Example input, example output. – JB Nizet Feb 22 '14 at 22:33
  • @JBNizet sort in alphabetical order – assylias Feb 22 '14 at 22:33
  • Out of curiosity, why not just use a `List` or a `Set`? There is nothing unique about the word `company` such that you'd want to make it a hash key, and you could use a `Comparator` or a sorted implementation of one of those lists. – rpmartz Feb 22 '14 at 23:00

2 Answers2

1

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());
Devavrata
  • 1,785
  • 17
  • 30
1

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}]
wolfrevo
  • 6,651
  • 2
  • 26
  • 38