1

I've got a public List<FriendProfile> friends = new ArrayList<FriendProfile>();. I initialize the friends list by reading the information from the server. The FriendProfile object contains a int called private int userPosition;

Once the friends list has been initialized, I would like to sort the friends list by having the FriendProfile object with the highest userPosition at index 0 of the list and then sort by accordingly, index 1 with the second highest userPosition ...

I guess I could write an sorting algorithm, yet I'm looking for prewritten code (maybe the JDK has some methods to offer?)

Help is appreciated!

Luke Taylor
  • 9,481
  • 13
  • 41
  • 73
  • possible duplicate of [Sorting an ArrayList of Contacts based on name?](http://stackoverflow.com/questions/1814095/sorting-an-arraylist-of-contacts-based-on-name) And http://stackoverflow.com/questions/6957631/sort-java-collection – assylias Jun 26 '12 at 11:42
  • [Sorting Number in List View](http://himanshugpt.wordpress.com/2010/09/10/sorting-list-in-java/) – Venky Jun 26 '12 at 11:44

7 Answers7

6

Use Collections.sort() and specify a Comparator:

Collections.sort(friends,
                 new Comparator<FriendProfile>()
                 {
                     public int compare(FriendProfile o1,
                                        FriendProfile o2)
                     {
                         if (o1.getUserPosition() ==
                                 o2.getUserPosition())
                         {
                             return 0;
                         }
                         else if (o1.getUserPosition() <
                                      o2.getUserPosition())
                         {
                             return -1;
                         }
                         return 1;
                     }
                 });

or have FriendProfile implement Comparable<FriendProfile>.

hmjd
  • 120,187
  • 20
  • 207
  • 252
1

Implement Comparable Interface.

class FriendProfile implements Comparable<FriendProfile> {

    private int userPosition;

    @Override
    public int compareTo(FriendProfile o) {

        if(this.userPosition > o.userPosition){
            return 1;
        }
        return 0;
    }

}

Just Call the Collection.sort(List) method.

    FriendProfile f1=new  FriendProfile();
    f1.userPosition=1;
    FriendProfile f2=new  FriendProfile();
    f2.userPosition=2;
    List<FriendProfile> list=new ArrayList<FriendProfile>();
    list.add(f2);
    list.add(f1);
    Collections.sort(list);

The List will be sorted.

Akhi
  • 2,242
  • 18
  • 24
1

Now no need to Boxing (i.e no need to Creating OBJECT using new Operator use valueOf insted with compareTo of Collections.Sort..)

1)For Ascending order

Collections.sort(temp, new Comparator<XYZBean>() 
{
     @Override
     public int compare(XYZBean lhs, XYZBean rhs) {

       return Integer.valueOf(lhs.getDistance()).compareTo(rhs.getDistance());
      }
 });

1)For Deascending order

Collections.sort(temp, new Comparator<XYZBean>() 
{
     @Override
     public int compare(XYZBean lhs, XYZBean rhs) {

       return Integer.valueOf(rhs.getDistance()).compareTo(lhs.getDistance());
      }
 });
Pranav
  • 4,172
  • 3
  • 30
  • 31
0

Use Collections.Sort and write a custom Comparator that compares based on userPosition.

OpenSauce
  • 8,533
  • 1
  • 24
  • 29
0

use Comparator with Collections.sort method

java.util.Collections.sort(list, new Comparator<FriendProfile >(){
     public int compare(FriendProfile a,  FriendProfile b){
          if(a.getUserPosition() > b.getUserPosition()){
             return 1;
           }else if(a.getUserPosition() > b.getUserPosition()){
            return -1;
         }
          return 0;
     }
});

see this link

Community
  • 1
  • 1
Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
0

There are two ways to do this.

1. FriendProfile could implement the interface Comparable.

public class FriendProfile implements Comparable<FriendProfile>
{
   public int compareTo(FriendProfile that)
   {
     // Descending order
     return that.userPosition - this.userPosition;
   }
}

...

Collections.sort(friendProfiles);

2. You could write a Comparator.

public class FriendProfileComparator implements Comparator<FriendProfile>
{
   public int compare(FriendProfile fp1, FriendProfile fp2) 
   {
     // Descending order
     return fp2.userPosition - fp1.userPosition;
   }
}

...

Collections.sort(friendProfiles, new FriendProfileComparator());

When comparing objects rather than primitives note that you can delegate on to the wrapper objects compareTo. e.g. return fp2.userPosition.compareTo(fp1.userPosition)

The first one is useful if the object has a natural order that you want to implement. Such as Integer implements for numeric order, String implements for alphabetical. The second is useful if you want different orders under different circumstances.

If you write a Comparator then you need to consider where to put it. Since it has no state you could write it as a Singleton, or a static method of FriendProfile.

Ben Thurley
  • 6,943
  • 4
  • 31
  • 54
0

You can use java.lang.Comparable interface if you want to sort in only One way.

But if you want to sort in more than one way, use java.util.Compartor interface.

eg:

The class whose objects are to be Sorted on its roll_nos

public class Timet {

    String name;
    int roll_no;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getN() {
        return roll_no;
    }
    public void setN(int n) {
        this.roll_no = n;
    }
    public Timet(String name, int n) {

        this.name = name;
        this.roll_no = n;
    }

    public String toString(){
        return this.getName();



    }

}

The class for sorting:

public class SortClass {


    public void go(){

        ArrayList<Timet> arr = new ArrayList<Timet>();
        arr.add(new Timet("vivek",5));
        arr.add(new Timet("alexander",2));
        arr.add(new Timet("catherine",15));

        System.out.println("Before Sorting :"+arr);





        Collections.sort(arr,new SortImp());

        System.out.println("After Sorting :"+arr);


    }
    class SortImp implements Comparator<Timet>{

        @Override
        public int compare(Timet t1, Timet t2) {




            return new Integer(t1.getN()).compareTo (new Integer((t2.getN())));
        }



    }
    public static void main(String[] args){

        SortClass s = new SortClass();
        s.go();

    }

}
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75