2

I have one array list

ArrayList itemListWithRank = ItemListDAO.getItemList();

and in arraylist itemListWithRank there are lots of type of objects values those all are different. And one value from them is item rank that also set with that array list.

Now i want to sort this array list based on accending order of rank. Rank value is already set in this array list.

How can i sort arraylist which one have lots of type of values....?

Thanks all....

krtek
26.7k5 gold badges60 silver badges84 bronze badges
asked Mar 15, 2011 at 8:27
5
  • 1
    Please give an example of the ArrayList content. Commented Mar 15, 2011 at 8:32
  • Do those objects in the list have anything in common? Some common interface or base class? How is the rank stored in the list? Can you give us an example? Commented Mar 15, 2011 at 8:32
  • Do you use generics? How is your ArrayList declared? What is the Type of the objects in the List? Commented Mar 15, 2011 at 8:33
  • arraylist contain price, name, quantity, unit rank of that item , etc. Commented Mar 15, 2011 at 8:36
  • as separate elements? In that case you're doing it wrong. You'll want one object per item with properties for each of those values. Commented Mar 15, 2011 at 8:48

5 Answers 5

6

Make them all object of a type. either design a common Base class or an Interface

and then

use Comparator to sort them out

For example.

public class SortableFields{
 protected long rank;
 //accessors methods
}

assumed that all the objects in arraylist are SortableFields now

Now

Collections.sort(list,new Comparator(){
public int compareTo(Object ob1,Object ob){
 return ((SortableFild)ob1.getRank())-((SortableFild)ob2.getRank())
}
});

Or use reflection hack , not preferable

Collections.sort(list,new Comparator(){
public int compareTo(Object ob1,Object ob){
 UtilClass.getRank(ob1)-UtilClass.getRank(ob); 
}
});

In your UtilClass

public int getRank(Object ob){
 Class cl=ob1.getClass();
 Method mthd=cl.getMethod("getRank");
 Integer output=(Integer)mthd1.invoke(ob);
 return output;
}
answered Mar 15, 2011 at 8:31

4 Comments

To be honest for such a basic question, I wouldn't even mention the reflection approach. And if you need to post it, then at least extract a getRank(Object) method and don't duplicate the code ;-)
@Joachim It is demonstration not the practical implementation :)
@Jigar: you'd be surprised how often the "simple demonstration" ends up in production code. It's unfortunate, but unavoidable, it seems. And we all end up having to maintain that code later on.
@jigar... can i sort arraylist wihout comparator..? I think without comparator its a junk code ... but it ok ... can i do this without comparator........?
4

Use Collections.sort(List<T> list, Comparator<? super T> c) and pass a custom comparator for your DAO objects.

It's by far easier if all of your list items share a common supertype that provides a method to get the item rank. Assuming you have such an interface, let's call it RankProvider, the comparator could look like:

public class Comparator<RankProvider> {
 @Override
 public int compare(RankProvider o1, RankProvider o2) {
 return o1.getItemRank().compareTo(o2.getItemRank());
 }
}

Pass an instance of this comparator or define an anonymous class.

Note - the example give above assumes, that the item rank is either a java primitive (like int) or a String or, in other words, is a Comparable (directly or after inboxing)


If you don't have a common superclass or interface, then comparing is less trivial. You'll either have to know all possible types and handle them each by each or you know that all types have the same method (name) and you can reflect the rank. One example for a comparator that compares known but random types:

public class Comparator { // no generics this time
 @Override
 public int compare(Object o1, Object o2) {
 Object[] comparables = new Object{o1, o2};
 int[] ranks = new int[2];
 for (int i = 0; i < 2; i++) {
 if (comparables[i] instanceof MyType1) {
 ranks[i] = ((MyType1) comparables[i]).getRank(); // rank getter for MyType1 type
 continue;
 }
 if (comparables[i] instanceof MyType2) {
 ranks[i] = ((MyType2) comparables[i]).getRank(); // rank getter for MyType2 type
 continue;
 }
 // ...
 }
 return ranks[0] - ranks[1]; // ascending order
 }
}

This could be done if you have no chance to refactor your DAOs to implement a shared interface.

answered Mar 15, 2011 at 8:32

1 Comment

Note, there are lots of type of objects values those all are different.
2
Collections.sort(itemListWithRank ,new Comparator<Person>() {
 public int compare(Person o1, Person o2) {
 return Integer.valueOf(o1.id).compareTo(Integer.valueOf(o2.id));
 }
});
answered Mar 15, 2011 at 8:39

Comments

1

Consider using lambdaj, which allows this construct

List<Person> sorted = sort(persons, on(Person.class).getAge());
answered Mar 15, 2011 at 9:42

Comments

0

First of all, every objects in the ArrayList must have some common parent in their hierarchy or implements an interface which define some way to get the rank. For example, all of them must implement this interface :

interface Rankable {
 public int getRank();
}

The you can create a custom Comparator :

Comparator<Rankable> myComparator = new Comparator<Rankable>() {
 public int compare(Rankable o1, Rankable o2) {
 return o1.getRank() - o2.getRank();
 }
 public equals(Object obj) {
 return obj == this;
 }
}

And finally sort your ArrayList :

Collections.sort(itemListWithRank, myComparator);

You can also implements Comparable in all your objects in the ArrayList and then the legacy sort method, but this will be less flexible if you're planning on doing other kind of comparison on them.

answered Mar 15, 2011 at 8:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.