Java 8 Lambda: Comparator

前端 未结 7 1460
鱼传尺愫
鱼传尺愫 2021-02-01 12:53

I want to sort a list with Lambda:

List messagesByDeviceType = new ArrayList();      
messagesByDeviceType.sort((Message o1, Messag         


        
7条回答
  •  长发绾君心
    2021-02-01 13:22

    Comparator

    We use comparator interface to sort homogeneous and heterogeneous elements for default, customized sorting order.

    int compare(T o1, T o2);
    

    it takes two arguments for ordering. Returns a

        negative integer(-1) « if first argument is less than the other
        zero             (0) « if both are equal
        positive integer (1) « if first greater than the second.
    

    Anonymous Classes how to sort a list of objects in prior versions of Java 8 using inner Classes.

    An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

    Comparator timeCompare = new Comparator() {
        @Override public int compare(Employee e1, Employee e2) {
            return e1.getCreationTime().compareTo( e2.getCreationTime() );
        }
    };
    

    Java 8 Lambda Expressions uing compare method

    A lambda expression is like a method: it provides a list of formal parameters and a body - an expression or block - expressed in terms of those parameters.

    LambdaExpression: LambdaParameters -> LambdaBody

    Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be declared final or be effectively final, or a compile-time error occurs where the use is attempted.

    Comparator functional_semantics = (e1, e2) -> {
       return e1.getCreationTime().compareTo( e2.getCreationTime() );
    };
    

    Basic Sort with Lambda Support

    Comparator timeCompareLambda = (o1, o2) -> (int) ( o1.getCreationTime() - o2.getCreationTime());
    Collections.sort(java8, timeCompareLambda );
    

    Using Extracted Key and Comparing method: A comparator that compares by an extracted key. Pass references using :: keyword.

    static  Comparator comparingLong(ToLongFunction keyExtractor)
    
    ToLongFunction keyExtracor = Employee::getCreationTime;
    Comparator byTime = Comparator.comparingLong( Employee::getCreationTime );
    

    Sample Test Code:

    public class Lambda_Long_Comparator {
        public static void main(String[] args) {
    
            List java7 = getEmployees();
    
            // Sort with Inner Class
            Comparator timeCompare = new Comparator() {
                @Override public int compare(Employee e1, Employee e2) {
                    return e1.getCreationTime().compareTo( e2.getCreationTime() );
                }
            };
    
            // Collections.sort(list); // Defaults to Comparable « @compareTo(o1)
            Collections.sort(java7, timeCompare); // Comparator « @compare (o1,o2)
            System.out.println("Java < 8 \n"+ java7);
    
            List java8 = getEmployees();
            Collections.sort(java8, Comparator
                    .comparing( Employee::getCreationTime )
                    .thenComparing( Employee::getName ));
            //java8.forEach((emp)-> System.out.println(emp));
            System.out.println("Java 8 \n"+java8);
        }
    
        static List getEmployees() {
            Date date = Calendar.getInstance().getTime();
            List list = new ArrayList();
            list.add( new Employee(4, "Yash", date.getTime()+7));
            list.add( new Employee(2, "Raju", date.getTime()+1));
            list.add( new Employee(4, "Yas", date.getTime()));
            list.add( new Employee(7, "Sam", date.getTime()-4));
            list.add( new Employee(8, "John", date.getTime()));
            return list;
        }
    }
    class Employee implements Comparable {
        Integer id;
        String name;
        Long creationTime;
    
        public Employee(Integer id, String name, Long creationTime) {
            this.id = id;
            this.name = name;
            this.creationTime = creationTime;
        }
    
        @Override public int compareTo(Employee e) {
            return this.id.compareTo(e.id);
        }
    
        @Override public String toString() {
            return "\n["+this.id+","+this.name+","+this.creationTime+"]";
        }
    
        // Other getter and setter methods
    }
    

    See these posts also:

    • Java 8 Tutorial
    • Java8 Lambdas vs Anonymous classes
    • Lambda vs anonymous inner class performance

提交回复
热议问题