Sorting ArrayList with Lambda in Java 8

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

提交回复
热议问题