Sorting ArrayList with Lambda in Java 8

前端 未结 11 2186
北荒
北荒 2020-12-29 18:08

Could somebody show me a quick example how to sort an ArrayList alphabetically in Java 8 using the new lambda syntax.

11条回答
  •  借酒劲吻你
    2020-12-29 18:45

    If you have an array with elements that have natural ordering (i.e String, int, double); then it can be achieved by:

    List myList = new ArrayList<>();
    myList.add("A");
    myList.add("D");
    myList.add("C");
    myList.add("B");
    myList.sort(Comparator.comparing(s -> s));
    myList.forEach(System.out::println);
    

    If on the another hand you have an array of objects and you want to sort base on some sort of object field, then you can use:

    class User {
        double score;
        // Constructor // Getters // Setters
    }
    
    List users = new ArrayList<>();
    users.add(new User(19d));
    users.add(new User(67d));
    users.add(new User(50d));
    users.add(new User(91d));
    
    List sortedUsers = users
            .stream()
            .sorted(Comparator.comparing(User::getScore))
            .collect(Collectors.toList());
    
    sortedUsers.forEach(System.out::println);
    

    If the sorting is more complex, then you would have to write your own comparator and pass that in.

提交回复
热议问题