2

I'm trying to use .sort() method with an arraylist.
My method public void sortSurname() should sort alphabetically all the objects by their surname, these objects are contained in an arraylist ArrayList<Contact> contacts.
Could someone please find the issue with this code?
Here is what I've written so far:
Contact class

package main;
public class Contact {
    private String name, surname, cellphone;
    private Genere genere;
    
    public Contact(String name, String surname, String cellphone){
        this.name=name;
        this.surname=surname;
        this.cellphone=cellphone;
    }

    public String getSurname() {
        return surname;
    }
}

Rubrica class

public class Rubrica {
    private ArrayList<Contact> contacts;
    
    public Rubrica(){
        contacts = new ArrayList<>();
    }

    public void sortSurname(){
        contacts.sort((Contact c1, Contact c2) -> {
            c1.getSurname().compareTo(c2.getSurname());
        });
    }

    public void addContact(Contact c1){
        contacts.add(c1);
    }
}

Main

package main;

public class Main {
public static void main(String[] args) {
    Contact c1 = new Contact("Paolo", "Groviera", "338");
    Contact c2 = new Contact("Paolo", "Groviera", "234");
    Contact c3 = new Contact("Lampa", "Dino", "234");
    Contact c4 = new Contact("Lampa", "Dina", "0234");
    
    Rubrica r = new Rubrica();
    r.addContact(c1);
    r.addContact(c2);
    r.addContact(c3);
    r.addContact(c4);

    r.sortSurname();
    System.out.println(r);
    }
}

Thank you for the help.

2
  • 2
    Please read How to create a Minimal, Reproducible Example. Then edit your question. Currently it is nicely minimal, but also completely unreproducible. Commented Apr 9, 2022 at 16:01
  • I have a problem also for this, I wrote the code in italian. The pieces above are translated, so what do you suggest me to do? Commented Apr 9, 2022 at 16:08

2 Answers 2

3

The problem is the {} which is a block and requires a return. Try it like this:

contacts.sort((Contact c1, Contact c2) -> {
   return  c1.getSurname().compareTo(c2.getSurname());
});

or forget the {} and just do

contacts.sort((Contact c1, Contact c2) -> 
    c1.getSurname().compareTo(c2.getSurname()));

or use the Comparator interface and pass a method reference.

contacts.sort(Comparator.comparing(Contact::getSurname));
Sign up to request clarification or add additional context in comments.

Comments

0

Get rid of the { }

public void sortSurname(){
    contacts.sort((Contact c1, Contact c2) -> 
        c1.getSurname().compareTo(c2.getSurname());
    );
}

Comments

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.