1

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?

0

3 Answers 3

6

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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;
        }
   }

Comments

0

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);
    }
});

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.