Sorting ArrayList with Lambda in Java 8

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

    Use list.sort(String::compareToIgnoreCase)

    Using list.sort(String::compareTo) or list.sort(Comparator.naturalOrder()) will give incorrect (ie. non-alphabetical) results. It will sort any upper case letter before all lower case letters, so the array ["aAAA","Zzz", "zzz"] gets sorted to ["Zzz", "aAAA", "zzz"]

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

    The syntax including a custom comparator is quite simple, and quick, for example here the ArrayList being sorted contains JSONObjects, and I will sort it based on a property called 'order':

    arrayList.sort((JSONObject o1, JSONObject o2)->o1.getInt("order")-o2.getInt("order"));
    

    I think this is a really nice and concise syntax, easy to read and less bulky than non-lambda syntax.

    0 讨论(0)
  • 2020-12-29 18:38
     List<Product> list = new ArrayList<>();
            List<String> list1 = new ArrayList<>();
            list.add(new Product(1));
            list.add(new Product(2));
            list.add(new Product(3));
            list.add(new Product(10));
     Collections.sort(list, Comparator.comparing((Product p) -> p.id));
            for (Product p : list) {
                System.out.println(p.id);
            }
    
    
    0 讨论(0)
  • 2020-12-29 18:41

    For strings this would work

    arrayList.sort((p1, p2) -> p1.compareTo(p2));
    
    0 讨论(0)
  • 2020-12-29 18:43

    Suppose you have List of names(String) which you want to sort alphabetically.

    List<String> result = names.stream().sorted(
                     Comparator.comparing(n->n.toString())).collect(Collectors.toList());
    

    its working perfectly.

    0 讨论(0)
  • 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));
    
    0 讨论(0)
提交回复
热议问题