comparator接口中compare原理

该博客展示了如何使用Java的Stream API对列表进行排序,特别是创建了一个自定义的Comparator来实现基于特定条件(权重)的排序。在这个例子中,作者对一个Student对象列表按ID进行排序,但当ID为1时赋予特殊权重,使其始终排在前面。博客内容涉及到Java编程、泛型、流API和自定义比较器的使用。
摘要由CSDN通过智能技术生成
package test;

import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class TestFunction {
    static class Student{
        String name;
        Integer id;

        public Student(String name, Integer id) {
            this.name = name;
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public Integer getId() {
            return id;
        }
    }

    public static void main(String[] args) {
        List<Student> list= Arrays.asList(new Student("jack",1),new Student("tom",11),new Student("tom",5),new Student("tom",10));
//        Integer reduce = list.stream().map((e) -> {
//            return e.getId();
//        }).reduce(0, (x, y) -> {
//            return x + y;
//        });
//        System.out.println(reduce);
        list.stream().sorted(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                System.out.println("o1="+o1.getId()+";o2="+o2.getId());
                if(o1.getId()==1)
                    return 1;
                if(o2.getId()==1)
                    return -1;
                return o1.getId()-o2.getId();
            }
        }).forEach((student -> System.out.println(student.getId())));
    }

}

  • Compare的返回值反应的是两个参数的权重,返回值为1时,前者(o1)权重大,返回值为-1时,后者(o2)权重大。然后排序结果按照权重(注意这里不是值的大小)由小到大进行排序。即权重默认升序排列。
  • 例:o1 =4 ,o2 = 6;
        return o2 – o1; {即返回值为正数,即为1,那么前者权重大,排序为o2,o1; 
    即为6,4,值降序排列}
        return o1 – o2; {即返回值为负数,即为-1,那么后者权重大,排序为o1,o2; 
    即为4,6,值升序排列}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值