fabianod
fabianod

Reputation: 693

Make an anonymous inner class a lambda in Java

I need to modify my code with the goal of (I quote) "make an anonymous inner class a lambda".

I have a suggestion to solve this problem, but not knowing how lambdas work in Java I don't know how to apply the suggestion to my specific case, can someone help me?

This is the suggestion I have

This is the "wrong" version:

myCollection.stream().map(new Mapper<String,String>() {
      public String map(String input) {
          return new StringBuilder(input).reverse().toString();
      }
});

And this is the "correct" version:

myCollection.stream().map(input -> new StringBuilder(input).reverse().toString());

Now, the "wrong" version in my code is this:

Collections.sort(commits, new Comparator<GitCommit>() {
    // @Override
    public int compare(GitCommit c1, GitCommit c2) {
        return c1.getDate().compareTo(c2.getDate());
        }
    });

What is the corresponding "correct" version?

Upvotes: 0

Views: 2317

Answers (3)

dreamcrash
dreamcrash

Reputation: 51393

Change this:

Collections.sort(commits, new Comparator<GitCommit>() {
    // @Override
    public int compare(GitCommit c1, GitCommit c2) {
        return c1.getDate().compareTo(c2.getDate());
        }
    });

to

Collections.sort(commits, (c1, c2) -> c1.getDate().compareTo(c2.getDate()));

You do not need to use Collections.sort you can simply call the List default method sort, namely:

commits.sort((c1, c2) -> c1.getDate().compareTo(c2.getDate()));

and simplified further by using method reference and the interface Comparator:

commits.sort(Comparator.comparing(GitCommit::getDate));

About the List default sort method:

default void sort(Comparator<? super E> c) Sorts this list according to the order induced by the specified Comparator.

Upvotes: 2

Nikolas
Nikolas

Reputation: 44368

In the first case, the method map requires Function. I assume it's wrong because of the Mapper. The code remains invalid as long as Mapper doesn't extend Function. This is a way to go:

interface Mapper<T, R> extends Function<T, R> {
    default R map(T t) {
        return apply(t);
    }
}
myCollection.stream().map(new Mapper<String,String>() {
    public String apply(String input) {
        return new StringBuilder(input).reverse().toString();
    }
});

The second case is correct and I assume your goal is to pack the anonymous function to:

  • A lambda expression:

    Collections.sort(commits, (c1, c2) -> c1.getDate().compareTo(c2.getDate()));
    
  • Or to a method reference:

    Collections.sort(commits, Comparator.comparing(GitCommit::getDate));
    

Upvotes: 2

A.Alexander
A.Alexander

Reputation: 598

Collections.sort(commits, Comparator.comparing(GitCommit::getDate));

or even

commits.sort(Comparator.comparing(GitCommit::getDate));

Upvotes: 3

Related Questions