Quantcast
Channel: How to sort List of objects by some property - Stack Overflow
Viewing all articles
Browse latest Browse all 19

Answer by djklicks-dhananjay for How to sort List of objects by some property

$
0
0

The best and the easiest way to sort any list of objects in Java (Java 8 and above).Lets sort a basket of fruits based on the property "fruitName"

Fruit POJO:

class Fruit{    int price;    String fruitName;    public Fruit(int price, String fruitName) {        super();        this.price = price;        this.fruitName = fruitName;    }    public int getPrice() {        return price;    }    public void setPrice(int price) {        this.price = price;    }    public String getFruitName() {        return fruitName;    }    public void setFruitName(String fruitName) {        this.fruitName = fruitName;    }    @Override    public String toString() {        return "Fruits [price=" + price +", fruitName=" + fruitName +"]";    }}

Now lets add fruits into a list and then sort it

List<Fruit> basketOfFruits = new ArrayList<>();        basketOfFruits.add(new Fruit(123, "oranges"));        basketOfFruits.add(new Fruit(45, "nectarine"));        basketOfFruits.add(new Fruit(369, "blueberries"));        basketOfFruits.add(new Fruit(248, "apple"));        basketOfFruits.add(new Fruit(968, "peaches"));        basketOfFruits.add(new Fruit(436, "grapes"));        basketOfFruits.add(new Fruit(596, "figs"));       //sorting by the property fruitName        Collections.sort(basketOfFruits, (f1, f2)->{return f1.getFruitName().compareTo(f2.getFruitName());}); 

You can now print the list (i.e basketOfFruits) and the fruits in the list would be sorted in ASCENDING order (lexicographically).The output would look like this:

[Fruits [price=248, fruitName=apple], Fruits [price=369, fruitName=blueberries], Fruits [price=596, fruitName=figs], Fruits [price=436, fruitName=grapes], Fruits [price=45, fruitName=nectarine], Fruits [price=123, fruitName=oranges], Fruits [price=968, fruitName=peaches]]

Instead of Collections.sort(), Java streams can also be used (Java 8 and above). The following is the code using Java streams

List<Fruit> sortedFruits = basketOfFruits.stream().sorted( (f1, f2)->{return f1.getFruitName().compareTo(f2.getFruitName());}).collect(Collectors.toList());

here the list is sorted in the same manner as Collections.sort(), but the sorted items would be stored/collected in another list "sortedFruits". So, if we want to print the sorted items of the list, we need to print "sortedFruits" instead of "basketOfFruits" in this case


Viewing all articles
Browse latest Browse all 19

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>