2

Comparator.comparing排序使用示例

 2 years ago
source link: https://segmentfault.com/a/1190000040835910
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Comparator.comparing排序使用示例

[TOC]

以前常用的排序方式是通过实现Comparator接口来进行排序,写法相对来说比较复杂,使用Comparator.comparing可以简化代码,看起来逻辑更清晰。

import lombok.Data;

/**
 * @Author: ck
 * @Date: 2021/10/12 3:51 下午
 */
@Data
public class Model {
    private String name;
    private int age;
}

通过实现Comparator接口来进行排序,代码相对较复杂

Collections.sort(models, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return o1.compareTo(o2);
    }
});

使用Comparator.comparing实现排序,同样可以指定按照哪个属性排序,且可以实现倒序。

package com.kaesar.java_common;

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

/**
 * Comparator.comparing 方法的使用
 *
 * @Author: ck
 * @Date: 2021/10/12 3:51 下午
 */
public class ComparatorTest {
    public static void main(String[] args) {
        List<Model> models = new ArrayList<>();
        Model model1 = new Model();
        model1.setAge(300);
        model1.setName("a");
        models.add(model1);

        Model model2 = new Model();
        model2.setAge(500);
        model2.setName("c");
        models.add(model2);

        Model model3 = new Model();
        model3.setAge(100);
        model3.setName("b");
        models.add(model3);

        System.out.println("-----排序前-----");
        // 排序前
        for (Model contract : models) {
            System.out.println(contract.getName() + " " + contract.getAge());
        }

        System.out.println("-----排序后,根据age排序-----");
        Collections.sort(models, Comparator.comparing(Model::getAge));
        // 排序后
        for (Model model : models) {
            System.out.println(model.getName() + " " + model.getAge());
        }

        System.out.println("-----排序后,根据age排倒序-----");
        Collections.sort(models, Comparator.comparing(Model::getAge).reversed());
        // 排序后
        for (Model model : models) {
            System.out.println(model.getName() + " " + model.getAge());
        }

        System.out.println("-----排序后,根据name排序-----");
        Collections.sort(models, Comparator.comparing(Model::getName));
        // 排序后
        for (Model model : models) {
            System.out.println(model.getName() + " " + model.getAge());
        }
    }
}

$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
相信坚持的力量!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK