Sorting an ArrayList of Objects alphabetically

前端 未结 5 569
一个人的身影
一个人的身影 2021-02-02 08:49

I have to create a method that sorts an ArrayList of objects alphabetically according to email and then prints the sorted array. The part that I am having trouble with

5条回答
  •  [愿得一人]
    2021-02-02 09:22

    The sorting part can be done by implementing a custom Comparator.

    Collections.sort(vehiclearray, new Comparator() {
        public int compare(Vehicle v1, Vehicle v2) {
            return v1.getEmail().compareTo(v2.getEmail());
        }
    });
    

    This anonymous class will be used for sorting the Vehicle objects in the ArrayList on the base of their corresponding emails alphabetically.

    Upgrading to Java8 will let you also implement this in a less verbose manner with a method reference:

    Collections.sort(vehiclearray, Comparator.comparing(Vehicle::getEmail));
    

提交回复
热议问题