简体   繁体   中英

How to sort multicolumn ArrayList

Suppose I have an arraylist as follows :

String[] s = {"John","Mary","Jane"};
double[] d = {18,21,34};

ArrayList<HashMap<String, CharSequence>> list1 = new ArrayList<HashMap<String, CharSequence>>();
for(int i = 0; i < 3; i++){
   HashMap<String, CharSequence> temp = new HashMap<String, CharSequence>();
   temp.put("col1", s[i]);
   temp.put("col2", Double.toString(d[i]));
   list1.add(temp);
}

If I want to sort any column in the list, how to do it? thank you.

infomation added :

I have try to write a comparator, but it can only sort for the first column. I don't know how to sort the second column.

Collections.sort(list1, new Comparator<HashMap<String, CharSequence>>() {
   @Override
   public int compare(HashMap<String, CharSequence> s1, HashMap<String, CharSequence> s2)
   {
      return  s1.toString().compareTo(s2.toString());
   }
});

Information added :

I have tried to modify the return statement, but it gets Nullpointer Exception :

return  s1.get(1).toString().compareTo(s2.get(1).toString());

Information added :

Thank you all. It seems that the HashMap has no indexer and caused NullPointer Exception, now the problem is solved by using column name:

return  s1.get("col2").toString().compareTo(s2.get("col2").toString());

Try something like this to sort according to your string s

Comparator<String> comparator = new Comparator<String>() {
             @Override
             public int compare(String key1, String key2) {
                 int returned = sequence.indexOf(key1) - sequence.indexOf(key2);
   //.indexOf(key1) returns the index of the first character of the String
                 if(returned < 0){ 
                         // then it is sorted; 
                   returned 1;
                 }

                 else{
                     returned = -1;}

                 return returned;
                }
         };
         Map<String,Double> lhm = new TreeMap<String,Double>(comparator);

This is not the solution for your problem but you can go by this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM