Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an ArrayList by an object's attribute in java [duplicate]

I wish to sort my objects in order of their Email address.

This is the method I've attempted but it does not work, but I'm not even sure it's the correct way to do what I want?

public static ArrayList<Billing> sortedListByEmail(ArrayList<Billing> Billing) {
    ArrayList<Billing> Sort = new ArrayList<Billing>();

    for (int i = 0; i < Sort.size(); i++) {
        Collections.sort(Sort, new Comparator<Billing>() {
            public int compare(Billing o1, Billing o2) {
                return o1.getEmail() > o2.getEmail() ? -1 : o1.getEmail().equals(o2.getEmail() ? 0 : 1);
            }
        });
    }

    return Sort;
}

Rest of the class:

import java.util.ArrayList;
import java.util.Collections;
import java.lang.Comparable;
import java.util.Comparator;

public class Billing extends User implements Comparable<User> {
    private Address billingAddress;
    private String email;

    public Billing(String id, String firstName, String lastName, String userName, String password, UserType userType, PermissionType permission, Boolean Status, Address billingAddress, String email) {
        super(id, firstName, lastName, userName, password, userType, permission, Status);

        this.billingAddress = billingAddress;
        this.email = email;
    }

    public Billing(String id, String firstName, String lastName, String userName, String password, UserType userType, PermissionType permission, Boolean Status, String email) {
        super(id, firstName, lastName, userName, password, userType, permission, Status);

    }

    public Billing(String id, String firstName, String lastName, String userName, String password, UserType userType, PermissionType permission, Boolean Status) {
        super(id, firstName, lastName, userName, password, userType, permission, Status);
    }

    public Address getBillingAddress() {
        return billingAddress;
    }

    public void setBillingAddress(Address billingAddress) {
        this.billingAddress = billingAddress;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

How would I accomplish sorting the objects in order of their email address? Thank you

like image 496
Nick Jam Avatar asked Nov 23 '25 03:11

Nick Jam


1 Answers

try the below code :

billingList.sort(Comparator.comparing(a -> a.getEmail));
like image 171
dassum Avatar answered Nov 24 '25 19:11

dassum