Skip to content
Advertisement

Sorting an arraylist with lambda function isn’t working

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.

Advertisement

Answer

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));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement