3

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?

1

3 Answers 3

5

You can use (assuming id is an int):

Collections.sort(list, Comparator.comparingInt(p -> p.id));
Sign up to request clarification or add additional context in comments.

2 Comments

Why complicate it more than this? It is not only simpler and shorter than the other answers, it is also less errorprone.
Or list.sort(Comparator.comparingInt(p -> p.id));, but both will end up at the same code in recent JREs.
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);

Comments

3

Like so:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.