Rithik_Star
Rithik_Star

Reputation: 661

How to sort a List of objects based on one variable using lambda expression?

I tried to use lambda expressions to sort the list of objects based on name in JDK 1.8. but it shows compilation error:

The left-hand side of an assignment must be a variable

Code:

    Train trains = new Train();
    trains.setName("Yerlin");
    trains.setCode("YYT");
    Train trains2 = new Train();
    trains2 .setName("Delhi");
    trains2 .setCode("DEH");
List<Train > traindetail= new ArrayList<Train >();
    traindetail.add(trains);
    traindetail.add(trains2);
    traindetail.stream().sorted(Train object1 , Train object2) -> object1.getName().compareTo(object2.getName()));

Upvotes: 1

Views: 1613

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200158

You are missing a paren:

airport.stream().sorted(Train object1 , Train object2) -> object1.getName().compareTo(object2.getName()));
                        ^--here

However, you would be advised to use a much more concise syntax:

airport.stream().sorted(Comparator.comparing(Train::getName));

Then there will be no parens to miss. With the Streams API usage we usally apply static imports liberally, so

airport.stream().sorted(comparing(Train::getName));

I see you don't assign the stream object and do not apply any terminal operations, so maybe you should be aware that the expression above has still taken no action on your data. You just declared that the stream will be sorted once you apply a terminal operation.

Upvotes: 5

user1907906
user1907906

Reputation:

Use

//                      v add ( here
airport.stream().sorted((Train object1 , Train object2) ->
  object1.getName().compareTo(object2.getName()));

Upvotes: 4

Related Questions