Sorting ArrayList with Lambda in Java 8

前端 未结 11 2176
北荒
北荒 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<String> 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<User> users = new ArrayList<>();
    users.add(new User(19d));
    users.add(new User(67d));
    users.add(new User(50d));
    users.add(new User(91d));
    
    List<User> 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.

    0 讨论(0)
  • 2020-12-29 18:46

    A really generic solution would be to introduce some StreamUtil like

    public class StreamUtil {
    
        private StreamUtil() {
        }       
    
        @SuppressWarnings({ "rawtypes", "unchecked" })
        public static <TYPE> Comparator<TYPE> sort(Function<TYPE, ? extends Comparable> getterFunction, boolean descending) {
            if (descending) {
                return (o1, o2) -> getterFunction.apply(o2).compareTo(getterFunction.apply(o1));
            }
            return (o1, o2) -> getterFunction.apply(o1).compareTo(getterFunction.apply(o2));
        }
    
    }
    

    The call would look something like

    list.stream().sorted(sort(YourClass::getSortProperty, true));
    
    0 讨论(0)
  • 2020-12-29 18:51

    Most concise:

    Collections.sort(stringList, String::compareToIgnoreCase);
    
    0 讨论(0)
  • 2020-12-29 18:57

    Lambdas shouldn't be the goal. In your case, you can sort it the same way as in Java 1.2:

    Collections.sort(list); // case sensitive
    Collections.sort(list, String.CASE_INSENSITIVE_ORDER); // case insensitive
    

    If you want to do it in Java 8 way:

    list.sort(Comparator.naturalOrder()); // case sensitive
    list.sort(String.CASE_INSENSITIVE_ORDER); // case insensitive
    

    You can also use list.sort(null) but I don't recommend this because it's not type-safe.

    0 讨论(0)
  • 2020-12-29 18:58

    In functional programming, you're not using the old objects to operate on them, but creating the new one in such a fashion:

    list.stream().sorted().map(blah-blah).filter(...)...
    
    0 讨论(0)
提交回复
热议问题