Java comparator

Normally, objects in Java can only be compared = = or= You can't use > <, but in actual development, we need to sort multiple objects, that is, we need to compare the size of objects

There are two ways to sort objects in Java:

1. Comparable natural sorting

public void test1(){
        String[] arr = new String[]{"AA","BB","DD","WW","MM","PP","CC"};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));//[AA,BB,CC,DD,MM,PP,WW]
    }

The custom class needs to be overridden

package com.atguigu.java1;

/**
 * @author MD
 * @create 2020-07-13 15:52
 */
public class Goods implements Comparable{
    private String name;
    private double price;

    public Goods() {
    }

    public Goods(String name,double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "name='" + name + '\'' +
                ",price=" + price +
                '}';
    }

    // 指明商品比较大小的方式:按照价格的方式从小到大,再按照商品名从低到高
    @Override
    public int compareTo(Object o) {
        if(o instanceof Goods){
            Goods goods = (Goods)o;
            // 方式一
            if (this.price > goods.price){
                return 1;
            }else if(this.price < goods.price){
                return -1;
            }else{
                //return 0;
                return this.name.compareTo(goods.name);
            }
            // 方式二:
            //return Double.compare(this.price,goods.price);
        }

        throw new RuntimeException("传入的参数不合法");

    }
}

// 测试
public void test2(){
        Goods[] arr = new Goods[4];
        arr[0] = new Goods("lx",123.12);
        arr[1] = new Goods("xm",23.12);
        arr[2] = new Goods("hw",67);
        arr[3] = new Goods("de",99);

        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
//[Goods{name='xm',price=23.12},Goods{name='hw',price=67.0},Goods{name='de',price=99.0},Goods{name='lx',price=123.12}]

    }

2. Comparator customized sorting

When the element type does not implement Java Lang. comparable interface, and it is not convenient to modify the code, or it implements Java The collation of the lang. comparable interface is not suitable for the current operation, so you can consider using the comparator object to sort

// 这里没有使用泛型,String已经重写了compareTo(obj)方法直接调
public void test3(){
        String[] arr = new String[]{"AA","CC"};
    // 这里使用匿名
        Arrays.sort(arr,new Comparator() {

            // 安装字符串从大到小
            @Override
            public int compare(Object o1,Object o2) {
                if (o1 instanceof String && o2 instanceof String){
                    String s1 = (String)o1;
                    String s2 = (String)o2;
                    return -s1.compareTo(s2);
                }
                throw new RuntimeException("输入不合法");
            }
        });
        System.out.println(Arrays.toString(arr));//[WW,AA]

    }

The default is from small to large. You can add symbols directly in front, that is, from high to low

String and wrapper classes have implemented compare() and can be called directly

public void test4(){
        Goods[] arr = new Goods[4];
        arr[0] = new Goods("lx",123.1);
        arr[1] = new Goods("lx",99);

        // 指明商品比较大小的方式,安装产品的名称从低到高排序,若名称一样,再安装价格从高到底排序
        Arrays.sort(arr,new Comparator<Goods>() {
            @Override
            public int compare(Goods o1,Goods o2) {
                if (o1.getName().equals(o2.getName())){
                    return -Double.compare(o1.getPrice(),o2.getPrice());
                }else{
                    return o1.getName().compareTo(o2.getName());
                }
            }
        });
        System.out.println(Arrays.toString(arr));
    //[Goods{name='de',price=123.1},price=23.12}]
    }

Comparison between comparable interface and comparator:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>