Sorting an ArrayList of objects using a custom sorting order

后端 未结 11 1504
说谎
说谎 2020-11-22 00:14

I am looking to implement a sort feature for my address book application.

I want to sort an ArrayList contactArray. Contact

11条回答
  •  [愿得一人]
    2020-11-22 00:59

    In addition to what was already posted you should know that since Java 8 we can shorten our code and write it like:

    Collection.sort(yourList, Comparator.comparing(YourClass::getFieldToSortOn));
    

    or since List now have sort method

    yourList.sort(Comparator.comparing(YourClass::getFieldToSortOn));
    

    Explanation:

    Since Java 8, functional interfaces (interfaces with only one abstract method - they can have more default or static methods) can be easily implemented using:

    • lambdas arguments -> body
    • or method references source::method.

    Since Comparator has only one abstract method int compare(T o1, T o2) it is functional interface.

    So instead of (example from @BalusC answer)

    Collections.sort(contacts, new Comparator() {
        public int compare(Contact one, Contact other) {
            return one.getAddress().compareTo(other.getAddress());
        }
    }); 
    

    we can reduce this code to:

    Collections.sort(contacts, (Contact one, Contact other) -> {
         return one.getAddress().compareTo(other.getAddress());
    });
    

    We can simplify this (or any) lambda by skipping

    • argument types (Java will infer them based on method signature)
    • or {return ... }

    So instead of

    (Contact one, Contact other) -> {
         return one.getAddress().compareTo(other.getAddress();
    }
    

    we can write

    (one, other) -> one.getAddress().compareTo(other.getAddress())
    

    Also now Comparator has static methods like comparing(FunctionToComparableValue) or comparing(FunctionToValue, ValueComparator) which we could use to easily create Comparators which should compare some specific values from objects.

    In other words we can rewrite above code as

    Collections.sort(contacts, Comparator.comparing(Contact::getAddress)); 
    //assuming that Address implements Comparable (provides default order).
    

提交回复
热议问题