Sorting ArrayList with Lambda in Java 8

前端 未结 11 2190
北荒
北荒 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:44

    Are you just sorting Strings? If so, you don't need lambdas; there's no point. You just do

    import static java.util.Comparator.*;
    
    list.sort(naturalOrder());
    

    ...though if you're sorting objects with a String field, then it makes somewhat more sense:

    list.sort(comparing(Foo::getString));
    

提交回复
热议问题