0

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.

2
  • That's not a lambda Comparator. It is simply an instance of an anonymous class. Commented Nov 17, 2020 at 3:21
  • Im new to lambdas so I dont know how to use them properly Commented Nov 17, 2020 at 3:24

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I need to do it with lambda
0

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

2 Comments

I need to do it in class
@sdavb Provide more code in your question and maybe I can help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.