zoukankan      html  css  js  c++  java
  • Java对象数组排序的三种方法->comparable,comparator,lambda表达式

    以Employee为例,实现对象数组Employee[] employees的排序

    1.类实现comparable

    一个对象数组若要使用Arrays.sort(Object[] objects)方法来排序,那么该对象类需要实现comparable接口

    public class Employee implements Comparable<Employee>{
        private String name;
        private double salary;
    
        public Employee(){
            name="Employee";
            salary=0;
        }
    
        public Employee(String name,double salary){
            this.name=name;
            this.salary=salary;
        }
    
        ...省略代码...
    
        public double getSalary(){
            return salary;
        }
    
        public void setSalary(double salary){
            this.salary=salary;
        }
    
        @Override
        public int compareTo(Employee o){
            //return Double.compare(salary,o.salary);
            return Double.compare(this.getSalary(),o.getSalary());
        }
    }
            //1.Employee实现Comparable接口
            Arrays.sort(employees);

    2.往Arrays.sort()方法中传入Comparator对象来规定排序规则

    class EmployeeComparator implements Comparator<Employee>{
        @Override
        public int compare(Employee o1,Employee o2){
            return Double.compare(o1.getSalary(),o2.getSalary());
        }
    }
            //2.使用Comparator比较器
            Comparator comparator=new EmployeeComparator();

    3.往Arrays.sort()方法传入lambda表达式

            //3.使用Lambada表达式
            Arrays.sort(employees,(o1,o2)->{
                if(o1.getSalary()>o2.getSalary())return 1;
                else return -1;
            });
  • 相关阅读:
    HDU3461 Code Lock 并查集应用
    记录,待总结8
    HDU1325 Is It A Tree?
    函数指针总结
    记录,待总结6
    HDU1272 小希的迷宫 并查集
    记录,待总结10
    记录,待总结9
    C# 获取radiobutton的值
    解决idea控制台tomcat输出中文乱码
  • 原文地址:https://www.cnblogs.com/ming-szu/p/9165393.html
Copyright © 2011-2022 走看看