Java:比较器Comparator的使用

郎家岭伯爵 2023年09月05日 336次浏览

前言

介绍下 Java 中 Comparator 的使用。

实现

理论

Comparator<YourObject> 是一个比较器对象。在 Java 中,Comparator 是一个函数式接口,用于定义两个对象之间的比较规则,从而允许我们自定义对象的排序顺序。

实现

业务场景一:按照自定义条件排序

例如我们自定义一个根据整数的绝对值进行排序的比较器:

@GetMapping("/t54")
public void test54(){
    List<Integer> list = Stream.of(1, -7, 3, -6, 5).collect(Collectors.toList());
    System.out.println("排序之前:" + list);

    Comparator<Integer> customComparator = Comparator.comparingInt(Math::abs);
    List<Integer> collect = list.stream()
            .sorted(customComparator)
            .collect(Collectors.toList());
    System.out.println("使用Comparator比较器进行绝对值排序之后:" + collect);
}

输出:

排序之前:[1, -7, 3, -6, 5]
使用Comparator比较器进行绝对值排序之后:[1, 3, 5, -6, -7]

业务场景二:按照对象属性排序

对一个包含对象的列表按照对象的某个属性进行排序。

例如我们有一个包含用户对象的列表,按照用户的年龄进行排序:

@GetMapping("/t55")
public void test55(){
List<UserEntity> list = Stream.of(new UserEntity().setUserName("小明").setAge(15),
        new UserEntity().setUserName("小红").setAge(30),
        new UserEntity().setUserName("小强").setAge(25)).collect(Collectors.toList());
System.out.println("排序之前:" + list);

Comparator<UserEntity> userEntityComparator = Comparator.comparingLong(UserEntity::getAge);
List<UserEntity> collect = list.stream()
        .sorted(userEntityComparator)
        .collect(Collectors.toList());
System.out.println("使用Comparator比较器排序之后:" + collect);

List<UserEntity> collect1 = list.stream()
        .sorted(userEntityComparator.reversed())
        .collect(Collectors.toList());
System.out.println("把Comparator按倒序进行排序:" + collect1);
}

输出:

排序之前:[UserEntity(id=null, userName=小明, password=null, age=15), UserEntity(id=null, userName=小红, password=null, age=30), UserEntity(id=null, userName=小强, password=null, age=25)]
使用Comparator比较器排序之后:[UserEntity(id=null, userName=小明, password=null, age=15), UserEntity(id=null, userName=小强, password=null, age=25), UserEntity(id=null, userName=小红, password=null, age=30)]
把Comparator按倒序进行排序:[UserEntity(id=null, userName=小红, password=null, age=30), UserEntity(id=null, userName=小强, password=null, age=25), UserEntity(id=null, userName=小明, password=null, age=15)]

业务场景三:Map类型的数据

我们按照 Map 的键的长度进行比较:

@GetMapping("/t56")
public void test56(){
Map<String, Integer> myMap = new HashMap<>();
myMap.put("apple", 3);
myMap.put("banana", 2);
myMap.put("cherry", 1);
myMap.put("date", 4);
System.out.println("排序之前:" + myMap);

// 创建一个Comparator对象,按键长度进行排序
Comparator<String> keyComparator = Comparator.comparing(String::length);

Map<String, Integer> sortedMap = myMap.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByKey(keyComparator))
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (e1, e2) -> e1,
                LinkedHashMap::new
        ));
System.out.println("使用比较器排序之后:" + sortedMap);
}

输出:

排序之前:{banana=2, date=4, apple=3, cherry=1}
使用比较器排序之后:{date=4, apple=3, banana=2, cherry=1}

总结

Java 中 Comparator 的使用。

赞助页面示例