2

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?

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
Ashvin
  • 35
  • 1
  • 1
  • 5
  • 2
    Possible duplicate of [java 8, Sort list of objects by attribute without custom comparator](http://stackoverflow.com/questions/33487063/java-8-sort-list-of-objects-by-attribute-without-custom-comparator) – Draken May 22 '17 at 08:23

3 Answers3

5

You can use (assuming id is an int):

Collections.sort(list, Comparator.comparingInt(p -> p.id));
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
  • 2
    Why complicate it more than this? It is not only simpler and shorter than the other answers, it is also less errorprone. – Ole V.V. May 22 '17 at 08:26
  • 4
    Or `list.sort(Comparator.comparingInt(p -> p.id));`, but both will end up at the same code in recent JREs. – Holger May 22 '17 at 17:44
3

Like so:

  Collections.sort(list,(p1,p2)->Integer.compare(p1.id, p2.id));
Ted Cassirer
  • 364
  • 1
  • 10
2

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);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97