欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA 使用Comparator接口实现自定义排序

程序员文章站 2022-05-23 18:14:37
...

1、原则
Comparator接口可以实现自定义排序,实现Comparator接口时,要重写compare方法:
int compare(Object o1, Object o2) 返回一个基本类型的整型
如果要按照升序排序,则o1 小于o2,返回-1(负数),相等返回0,01大于02返回1(正数)
如果要按照降序排序,则o1 小于o2,返回1(正数),相等返回0,01大于02返回-1(负数)

2、示例代码

package com.zte.ums.zenap.pm.task.message;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class UserComparator implements Comparator < User > {

    public static void main( String[] args ) {
        List < User > users = new ArrayList < User >();
        users.add( new User( 10, "a" ) );
        users.add( new User( 11, "d" ) );
        users.add( new User( 15, "s" ) );
        users.add( new User( 6, "x" ) );
        users.add( new User( 17, "a" ) );
        users.add( new User( 17, "b" ) );
        users.add( new User( 17, "c" ) );
        users.add( new User( 17, "d" ) );
        UserComparator comparator = new UserComparator();

        users.sort( comparator );
        // 也可以使用:Collections.sort( users, comparator );

        for ( User u : users ) {
            System.out.println( u );
        }
    }

    @Override
    public int compare( User u1, User u2 ) {
        if ( u1.equals( u2 ) ) {
            return 0;
        }
        else if ( u1.getAge() < u2.getAge() ) {
            return 1;
        }
        else if ( u1.getAge() == u2.getAge() ) {
            int f = u1.getName().compareTo( u2.getName() );
            if ( f < 0 ) {
                return -1;
            }
            return 0;
        }
        else {
            return -1;
        }
    }
}

class User {
    private int age;
    private String name;

    public User() {

    }

    public User( int age, String name ) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge( int age ) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName( String name ) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User [age=" + age + ", name=" + name + "]";
    }

}

运行结果:

User [age=17, name=a]
User [age=17, name=b]
User [age=17, name=c]
User [age=17, name=d]
User [age=15, name=s]
User [age=11, name=d]
User [age=10, name=a]
User [age=6, name=x]
相关标签: java 排序