简体   繁体   中英

What's alternative NSSortDescriptor in Java?

I hava ArrayList which is include Custom Data Class.

ArrayList<MyData> list

Custom Data class has several field

class MyData {
   private int num;
   private String name;

   etc....

   getter/setter...
}

I want to sort List by field (ex:num)

Objecitive-C has NSSortDescriptor which can sort objects.

NSSortDescriptor Class Reference

is There alternative this? or other solution?

You can use Comparable and Comparator interface.. and the use Collection.sort().

You need to implement Comparable and Comparator interface, if you are using Collection of Custom Type(ie not primitive types).

For detailed examples check http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

Hope this post will be helpful to u.

java.util.Comparator coupled with java.util.Collection.sort should do the trick.

You could also have MyData implement java.util.Comparable and use the other sort method, but that isn't quite as flexible.

There is nothing similar to NSSortDescriptor in Java: Java sorting uses the style that is more similar to the sortUsingComparator: method of the NSMutableArray class:

Collections.sort(list, new Comparator<MyData>() {
    // This is similar to the comparator block of Cocoa
    public int compare(MyData o1, MyData o2) {
        // Put the comparison code here
        ...
    }
});

Implement Comparable or Comparator and use Collections.sort() .

Comparable

public class MyClass implements Comparable<MyClass>{
    public int x;

    public int compareTo(MyClass mc){
        return x - mc.x;
    }
}

Comparator

public class MyClass{
    public int x;
}

public class MyClassComparator implements Comparator<MyClass>{
    public int compare(MyClass mc1, MyClass mc2){
        return mc1.x - mc2.x;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM