2
头图

Comparator.comparing sort usage example

[TOC]

background

used to sort by implementing the Comparator interface. The writing method is relatively complicated. Using Comparator.comparing can simplify the code and make the logic clearer.

Entity class

import lombok.Data;

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

Example one

Sort by implementing the Comparator interface, the code is relatively complex
Collections.sort(models, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return o1.compareTo(o2);
    }
});

Example two

Using Comparator.comparing to achieve sorting, you can also specify which attribute to sort according to, and you can achieve reverse order.
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$
believe in the power of persistence!

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!