Reputation: 661
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
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
Reputation:
Use
// v add ( here
airport.stream().sorted((Train object1 , Train object2) ->
object1.getName().compareTo(object2.getName()));
Upvotes: 4