List中根据某个实体的属性去重或者排序

引言

最近在在项目中对list的一些操作还是比较多的,其中有很多内置的工具类都很强大,但是这些都是对于基本类型的操作,但是我们在项目中操作最多的是我们自定义的对象,所以一些操作还是需要我们自己来封装的,下面以排序和去重为例子。

一、去重

实体如下:

public class RobotCase implements Serializable {
    /**
     * 案件id
     */
    private Long caseId;

    /**
     * 自增id
     */
    private Long partnerId;

    /**
     * 甲方公司名称
     */
    private String clientName;

    /**
     * 借款人姓名
     */
    private String borrowerName;

    /**
     * 借款人性别 1 男 0 女
     */
    private Byte borrowerSex;

    /**
     * 借款人电话
     */
    private String borrowerTel;

    。。。。。。。。
}

根据RobotCase实体中的borrowerTel字段进行去重,代码如下:

 /**
     * @param
     * @return
     * @description 根据电话号码去重
     * @date 14:39 2018/6/19
     * @author zhenghao
     */
    private List<RobotCase> removeDuplicateCase(List<RobotCase> cases) {
        Set<RobotCase> set = new TreeSet<>(new Comparator<RobotCase>() {
            @Override
            public int compare(RobotCase o1, RobotCase o2) {
                //字符串,则按照asicc码升序排列
                return o1.getBorrowerTel().compareTo(o2.getBorrowerTel());
            }
        });
        set.addAll(cases);
        return new ArrayList<>(set);
    }


二、排序

public class Student {
  private int age; 
  private String name; 
   。。。
}

具体实现

 /* 
        * int compare(Student o1, Student o2) 返回一个基本类型的整型, 
        * 返回负数表示:o1 小于o2, 
        * 返回0 表示:o1和o2相等, 
        * 返回正数表示:o1大于o2。 
        */
    public List<Student>sort(List<Student>students){
        Collections.sort(students, new Comparator<RobotCase>() {
            @Override
            public int compare(Student  o1, Student  o2) {
                //按照学生的年龄进行升序排列 ;<是降序
          if(o1.getAge() > o2.getAge()){
            return 1;
          }
          if(o1.getAge() == o2.getAge()){
            return 0;
          }
          return -1;

          return o1.getAge()-o2.getAge();//升序
          return o2.getAge()-o1.getAge();//降序
                return o1.getName().compareTo(o2.getName()) ;// 按照姓名升序
          return o2.getName().compareTo(o1.getName()) ;// 按照姓名降序
            }
        });
        return students;
    }


  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

g-Jack

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值