Archives par mot-clé : tri

Trier une liste en Java

Publié dans Snippet | Laisser un commentaire
Collections.sort(myList, new MyComparator());

public class MyComparator implements Comparator<MyObject> {
    @Override
    public int compare(MyObject o1, MyObject  o2) {
        if (o1.getInt() == o2.getInt()) {
            return 0;
        }
        if (o1.getInt() < o2.getInt()) {
            return -1;
        }
        return 1;
    }
}

Trier un array en Javascript

Publié dans Snippet | Laisser un commentaire

Simple sort

var myArray = ["var2", "var1", "var3"];
console.log("Before:", myArray); // Output: "Before: ["var2", "var1", "var3"]"
myArray.sort();
console.log("After:", myArray); // Output: "After: ["var1", "var2", "var3"]"

More complex sort

var myComplexArray = [{"id":"3", "data":"var2"}, {"id":"2", "data":"var1"}, {"id":"1", "data":"var3"}];
console.log("Before:", myComplexArray ); // Output: "Before: [{"id":"3", "data":"var2"}, {"id":"2", "data":"var1"}, {"id":"1", "data":"var3"}]"
myComplexArray .sort(function(a, b){ return a.id < b.id; });
console.log("After:", myComplexArray ); // Output: "After: [{"id":"1", "data":"var3"}, {"id":"2", "data":"var1"}, {"id":"3", "data":"var2"}]"