Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Lambda expression, I want to sort by integer values using the Java language

Tags:

java

lambda

Using Lambda expression, I want to sort integer values using the Java language

public class Test_LAMBDA_Expression {

public static void main(String[] args) {

    List<Test_Product> list= new ArrayList<Test_Product>();

    list.add(new Test_Product(1,"HP Laptop",25000f));  
    list.add(new Test_Product(2,"Keyboard",300f));  
    list.add(new Test_Product(2,"Dell Mouse",150f));
    list.add(new Test_Product(4,"Dell PC",150f));
    list.add(new Test_Product(5,"Dell Printer",150f));


    System.out.println("Sorting by name");

    Collections.sort(list,(p1,p2)->{
        return p1.name.compareTo(p2.name);
    });

    for(Test_Product p: list){
        System.out.println(p.id+" "+p.name+" "+p.price);
     }
  }

}

Now I want to sort using id. How can I do that?

like image 754
Ashvin Avatar asked Apr 23 '26 04:04

Ashvin


2 Answers

You can use (assuming id is an int):

Collections.sort(list, Comparator.comparingInt(p -> p.id));
like image 133
Thomas Fritsch Avatar answered Apr 25 '26 16:04

Thomas Fritsch


you can use a lambda and get the id to compare those elements in the list

list.sort((x, y) -> Integer.compare(x.getId(), y.getId()));
System.out.println(list);
like image 43
ΦXocę 웃 Пepeúpa ツ Avatar answered Apr 25 '26 17:04

ΦXocę 웃 Пepeúpa ツ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!