简体   繁体   中英

Sorting list of objects from another Class with lambda in Java

In my taks I need to sort names with lambda. Class lambdaComparator extends class Car.

I make class LambdaComparator like this:

public class LambdaComparator extends Car

public LambdaComparator(String name) {super(name);}

In this class I need to sort objects of type Car.

In main class I have list of objects and with function I need to sort it.

In class LambdaComparator I have this:

Collections.sort(list, new Comparator<Car>() {
         public int compare(Car x, Car y) {
            return x.getName().compareTo(y.getName()));
         }
      });

How should I call function in main to get this sorted, should I make function of type void in class to somehow call it.

Edit: lambda expression

class LambdaSort<T extends Car>
private List<T> listOfCars;

public LambdaComparator(){
this.listOfCars = new ArrayList<T>();
}

 public void sortCars(T cars)
listOfCars.sort((Car o1, Car o2)->o1.getName().compareTo(o2.getName());

In main function I add objects of type car to that list.

A lambda comparator would be something like this.

Comparator<Car> comp = (c1, c2)-> c1.getName().compareTo(c2.getName());

In the above example, the Comparator is comparing on a specific field of the Car class, name . Since name probably returns a string, one can use compareTo since the String class implements the Comparable (not Comparator ) interface for comparing Strings.

But the lambda could be specified much more easily using one of the methods in the Comparator interface. The comparing method may take a lambda or a method reference (shown below).

Comparator<Car> comp = Comparator.comparing(Car::getName);

Then when it is passed to the sort method, the sort method will apply it to the objects under sort as comp.compare(obj1, obj2) (although it may not be called comp in the method that uses it)

For more information, check out The Java Tutorials

Take a look at what lambda is here .

If you have a list in your main class, it's as simple as just sorting it. You probably don't even need the class LambdaComparator .

        List<Car> list = new ArrayList<>();
        Collections.sort(list, (a, b) -> a.getName().compareTo(b.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