简体   繁体   中英

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

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.

Use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM