Stack Overflow archive
4 scoreaccepted

Ordering array by a property in Java

score
4
question views
133
license
CC BY-SA 3.0

Something like this:

java
Arrays.sort(products, new Comparator<Product>() {

    @Override
    public int compare(Product p1, Product p2) {
        if (p1.getPrice() > p2.getPrice()) return -1;
        if (p1.getPrice() < p2.getPrice()) return 1;
        return 0;
    }

});

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.