-1
import java.util.*;  
import java.io.*; 

class Simpson implements Comparable<Simpson> {
    String name;

    Simpson(String name) {
        this.name = name;
    }

    @Override
    ( simpson) -> {
        return this.name.compareTo(simpson.name);
    }
}

public class Main {

     public static void main(String... sortingWithList) {
        List<Simpson> simpsons = new ArrayList<>();
        simpsons.add(new Simpson("Homer "));
        simpsons.add(new Simpson("Marge "));
        simpsons.add(new Simpson("Bart "));
        simpsons.add(new Simpson("Lisa "));

        Collections.sort(simpsons);
        simpsons.stream().map(s -> s.name).forEach(System.out::print);

I want to use a lambda expression for a comparable, but I am getting an error.

3
  • Why did you want to implement lambda on a class? Commented Apr 10, 2021 at 0:51
  • Your code seems incomplete. I suggested an edit to format it properly. Please tell us which error you got (edit and post error Output as text). Do you just want to sort the names alphabetically? Commented Apr 10, 2021 at 0:56
  • 1
    There is a JEP draft: Concise Method Bodies. openjdk.java.net/jeps/8209434 I don't know whether any progress has been made to integrating it yet. In the mean time, just use a standard public method. Commented Apr 10, 2021 at 1:04

3 Answers 3

1

Use this instead of Collections.sort:

simpsons.sort((s1, s2) -> s1.compareToIgnoreCase(s2));
Sign up to request clarification or add additional context in comments.

1 Comment

Is sort on collections persistent (does it modify them) or does it just return a sorted collection (immutable)? As learner I would ask😉
0

Have a look at the Java Doc for interface Comparable<T>.

It provides a method to compare this object against another object (passed in parameter o) of the same type (in your case: T is Simpson)

int compareTo(T o)

Also your name properties are already comparable, because of type String, which implements this interface too. So you can simply delegate (as you already well did).

Supposed error

Please correct the method signature, it's currently incomplete and might be the cause of a compilation error:

@Override ( simpson) -> { return this.name.compareTo(simpson.name); . }

Fix issues

Give the method the same name and return type and parameters as prescribed by the interface:

public int compareTo(Simpson o) {
    if (o == null || this.name == null) return -1; // could adjust to your needs to avoid NPE
    return this.name.compareTo( o.name );
}

Most important: since interfaces are to be called from outside, the implemented methods must be public!

Just lambda

Or just go by streaming with appropriate lambda expression as suggested in previous answer 😉

simpsons.stream()
    .map(s -> s.name) // map serves like delegation to name
    .sorted((s1, s2) -> s1.compareToIgnoreCase(s2)) // sort previous with current element, here: names alphabetically
    .forEach(System.out::print);

Difference when sorting in streams:

  • use sorted(), not sort() like for collections
  • you can specify a Comparator as functional or lambda expression
  • you can also sort by natural order (as illustrated in following question)

There is yet another, simpler way to sort strings lexicographically:

Java 8 Stream sorting List of String

Comparator and natural-order

You can also combine both: (1) comparable interface, implemented by Simpson (2) stream with functional, sorted by comparator or lambda expression (as suitable).

simpsons.stream() 
   .sorted((s1, s2) -> s1.compareTo(s2)) // sort previous with current Simpson ! explicit comparator passed as lambda
   .forEach( s -> System.out.println(s.name) );  // print name of Simpson in new line

In the simple case, you don't need to 😜

Or you can use intelligent sorting and ! implicitly reuse the existing natural order by replacing with .sorted(). Try also what happens out-of-the-box (without any compareTo ⁉️):

class Simpson {
    String name;

    Simpson(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }

}

// main omitted, just the usage example:
simpsons.stream().sorted().forEach(System.out::println );

Sorting naturally would fallback to use toString if otherwise not comparable. Same way printing uses toString.

Does it sort correctly and print appealing❔

2 Comments

I am new to lambda expression. As lambda expression is using functional interface, comparable is also a functional interface. So how can I use lambda expression over here. Like we can use for comparator interface.
@SonamBanerjee No problem, I recognized already. As soon as your Simpson claas is correctly Comparable you can just use sorted() on streams of Simpson objects. Then they "follow" a natural order: means the -able interface is used as -ator functional by default. See Comparator tutorial
0

I believe the issue is that you are implementing Comparable, which means it implements the compareTo method.

import java.util.*;  
import java.io.*; 

class Simpson implements Comparable<Simpson> {
    String name;

    Simpson(String name) {
        this.name = name;
    }

    @Override
    int compareTo(Simpson other){
        return this.name.compareTo(other.name);
    }
}

public class Main {

     public static void main(String... sortingWithList) {
        List<Simpson> simpsons = new ArrayList<>();
        simpsons.add(new Simpson("Homer "));
        simpsons.add(new Simpson("Marge "));
        simpsons.add(new Simpson("Bart "));
        simpsons.add(new Simpson("Lisa "));

        Collections.sort(simpsons);
        simpsons.stream().map(s -> s.name).forEach(System.out::print);

     }

}

1 Comment

Yes OP tried to implement, but apparently forgot the name, return type, visibility. May I remind you that neither the code of question, nor yours will run (syntax).

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.