Ashvin
Ashvin

Reputation: 45

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

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?

Upvotes: 3

Views: 11350

Answers (3)

Thomas Fritsch
Thomas Fritsch

Reputation: 10147

You can use (assuming id is an int):

Collections.sort(list, Comparator.comparingInt(p -> p.id));

Upvotes: 5

Ted Cassirer
Ted Cassirer

Reputation: 364

Like so:

  Collections.sort(list,(p1,p2)->Integer.compare(p1.id, p2.id));

Upvotes: 3

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);

Upvotes: 3

Related Questions