Sorting List<> by numeric value

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-16 00:54:10

问题


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!


回答1:


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>.




回答2:


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.




回答3:


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



回答4:


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




回答5:


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




回答6:


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.




回答7:


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

    }

}


来源:https://stackoverflow.com/questions/11206495/sorting-list-by-numeric-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!