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

怎甘沉沦 提交于 2020-01-30 08:40:43

问题


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


回答1:


try the below code :

billingList.sort(Comparator.comparing(a -> a.getEmail));



回答2:


Since the email is a String and also a Comparable you can use the String.compareTo to sort using the email property. (This is a pre Java-8 solution):

public static List<Billing> sortedListByEmail(List<Billing> Billing) {
    List<Billing> sort = new ArrayList<>(Billing);
    Collections.sort(sort, new Comparator<Billing>() {
            public int compare(Billing o1, Billing o2) {
                   return o1.getEmail().compareTo(o2.getEmail());
            }
      }
   );
   return sort;
}

In Java-8 this can be made more compact, with the Comparator#comparing:

public static List<Billing> sortedListByEmail(List<Billing> Billing) {
        List<Billing> sorted = new ArrayList<>(Billing);
        sorted.sort(Comparator.comparing(b -> b.getEmail()));
        return sorted;
}

Here the original list supplied is not sorted in place, instead a copy is made which is sorted.

Or you can use Stream#sorted to do it in an elegant way which will also return you a new List instead of modifying the original one:

public static List<Billing> sortedListByEmail(List<Billing> Billing) {
    return Billing.stream()
                  .sorted(Comparator.comparing(b -> b.getEmail()))
                  .collect(Collectors.toList());
}



回答3:


If you want to do it old ways then got for below code

    public static ArrayList<Billing> sortedListByEmail(ArrayList<Billing> Billing) {

    Collections.sort(Billing, new Comparator<Billing>() {
        public int compare(Billing o1, Billing o2) {
            return o1.getEmail().compareTo(o2.getEmail());
        }
    });

    return Billing;
}

Few things you are doing wrong in your code - First - return o1.getEmail() > o2.getEmail() ? -1 : o1.getEmail().equals(o2.getEmail() ? 0 : 1); you cannot compare a string value like integer value.

Second - You are creating an empty array list and sorting it. It has no elements, it is empty. ArrayList<Billing> Sort = new ArrayList<Billing>(); ........ Collections.sort(Sort, new Comparator<Billing>() {

With java 8 features it can be done in very less line of code as below

billing.sort(Comparator.comparing(b -> b.getEmail()));



回答4:


This will change the existing array, no need of new variable,

Collections.sort(billingList, Comparator.comparing(Billing::getEmail));



回答5:


With considering that Billing List object name is billingList

1) If you are using Java 8 you can do it using below approaches:

Using Collections.sort with Lambda expression:

Collections.sort(billingList, (b1, b2) -> b1.getEmail().compareTo(b2.getEmail()));

Using sort method of List Interface (default method)

billingList.sort(Comparator.comparing(Billing::getEmail));

2) If you are using earlier version of Java

Collections.sort(billingList, new Comparator<Billing>() {

      public int compare(final Billing b1, final Billing b2) {

        return b1.getEmail().compareTo(b2.getEmail());

      };
    }); 


来源:https://stackoverflow.com/questions/57870812/sort-an-arraylist-by-an-objects-attribute-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!