-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.

Henry Twist
  • 5,666
  • 3
  • 19
  • 44
  • Why did you want to implement lambda on a class? – albertjtan Apr 10 '21 at 00: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? – hc_dev Apr 10 '21 at 00:56
  • 1
    There is a JEP draft: Concise Method Bodies. https://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. – Tom Hawtin - tackline Apr 10 '21 at 01:04

3 Answers3

1

Use this instead of Collections.sort:

simpsons.sort((s1, s2) -> s1.compareToIgnoreCase(s2));
Henry Twist
  • 5,666
  • 3
  • 19
  • 44
sanjeevRm
  • 1,541
  • 2
  • 13
  • 24
  • Is `sort` on collections persistent (does it modify them) or does it just return a sorted collection (immutable)? As learner I would ask – hc_dev Apr 10 '21 at 02:00
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);

     }

}

  • 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). – hc_dev Apr 10 '21 at 01:57
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❔

hc_dev
  • 8,389
  • 1
  • 26
  • 38
  • 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. – Sonam Banerjee Apr 10 '21 at 01:28
  • @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](https://www.javaguides.net/2020/04/java-8-stream-sorting-with-comparator.html) – hc_dev Apr 10 '21 at 02:09