Sorting an ArrayList of Objects alphabetically

前端 未结 5 625
一个人的身影
一个人的身影 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:23

    Although the question already has an accepted answer I would like to share some Java 8 solution

    // if you only want to sort the list of Vehicles on their email address
    Collections.sort(list, (p1, p2) -> p1.getEmail().compareTo(p2.getEmail()));
    

    .

    // sort the Vehicles in a Stream
    list.stream().sorted((p1, p2) -> p1.getEmail().compareTo(p2.getEmail()));
    

    .

    // sort and print with a Stream in one go
    list.stream().sorted((p1, p2) -> p1.getEmail().compareTo(p2.getEmail())).forEach(p -> System.out.printf("%s%n", p));
    

    .

    // sort with an Comparator (thanks @Philipp)
    // for the list
    Collections.sort(list, Comparator.comparing(Vehicle::getEmail));
    // for the Stream
    list.stream().sorted(Comparator.comparing(Vehicle::getEmail)).forEach(p -> System.out.printf("%s%n", p));
    

提交回复
热议问题