Comparator.comparing example of sorting use
[TOC]
background
In the past, the common sorting method was to implement the Comparator interface, which was relatively complex to write. Using the Comparator.comparing feature simplified the code and made it more logical.
Entity class
import lombok.Data;
/ * * *@Author: ck
* @Date: 2021/10/12 3:51 下午
*/
@Data
public class Model {
private String name;
private int age;
}
Copy the code
The sample a
The code for sorting by implementing the Comparator interface is relatively complex
Collections.sort(models, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
returno1.compareTo(o2); }});Copy the code
Example 2
Using Comparator.comparing, you can also specify which attribute to sort by and reverse order.
package com.kaesar.java_common;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/** * The use of the Comparator.comparing method **@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("----- before -----");
/ / before ordering
for (Model contract : models) {
System.out.println(contract.getName() + "" + contract.getAge());
}
System.out.println("----- sort by age -----");
Collections.sort(models, Comparator.comparing(Model::getAge));
/ / sorted
for (Model model : models) {
System.out.println(model.getName() + "" + model.getAge());
}
System.out.println("-----, reverse order according to age -----");
Collections.sort(models, Comparator.comparing(Model::getAge).reversed());
/ / sorted
for (Model model : models) {
System.out.println(model.getName() + "" + model.getAge());
}
System.out.println("----- sort by name -----");
Collections.sort(models, Comparator.comparing(Model::getName));
/ / sorted
for (Model model : models) {
System.out.println(model.getName() + ""+ model.getAge()); }}}Copy the code
1.01365≈37.78343433291.01^{365} ≈ 37.78343433291.01365≈37.7834343329 0.99365≈0.025517964450.99^{365} ≈ 0.025517964450.99365≈0.02551796445