eldho
eldho

Reputation: 255

Sorting in a Array List of HashMaps

I have a data Structure as shown below:

public class VResultSetBean {
   private ArrayList<RowBean> rowBeans; 
}

public class RowBean {
    private HashMap<String, Object> columns;
}

I need to sort rowBeans based on value of one of the keys in HashMap columns. What is the most efficient way to do this with Java?

Upvotes: 1

Views: 686

Answers (3)

cyon
cyon

Reputation: 9548

Make RowBean implement Comparable and implement the compareTo method to pull out the value of that key and use it to decide the result of the comparison.

public class RowBean implements Comparable<RowBean> {

     private HashMap<String, Object> columns;

     @Override
     public int compareTo(RowBean other) {
          Object valOther = other.columns.get(...);
          Object valMine = columns.get(...);
          return comparison(valOther, valMine);
     }
}

Once RowBean is a Comparable you can sort using:

 Collections.sort(rowBeans);

Upvotes: 6

eldho
eldho

Reputation: 255

This is the final code snippet that worked for me. Thanks guys..

public class RowBean implements Comparable<RowBean> {
         HashMap<String, Object> columns;
        public int compareTo(RowBean other) {
             Object valOther = other.columns.get("CONVERSIONS");
             Object valMine = columns.get("CONVERSIONS");
             return comparison(valOther, valMine);
        }
        private int comparison(Object valOther, Object valMine) {
           if((Long) valMine > (Long)valOther) 
                return 1;
            else if((Long) valMine < (Long)valOther)
                return -1;
            else
                return 0;
        }
   }

Upvotes: 1

morgano
morgano

Reputation: 17422

First, there is no way to compare two objects of class Object, they need to have a way to get compared: this is implementing the interface Comparable. so you would need to change columns to be HashMap<String, Comparable>.

After that, you could add a comparing method to RowBean like this:

class RowBean {

    private HashMap<String, Comparable> columns;

    public int compare(String column, RowBean other) {
        return columns.get(column).compareTo(other.columns.get(column));
    }

}

And finally, to sort your list you could use an anonym Comparator, this way:

List<RowBean> list = new ArrayList<>();

final String sortingColumn = "myColumn";

Collections.sort(list, new Comparator<RowBean>() {
    @Override
    public int compare(RowBean o1, RowBean o2) {
        return o1.compare(sortingColumn, o2);
    }
});

Upvotes: 0

Related Questions