List集合去重

想整个简单的去重

package com.wangwei.common;

import java.util.*;

public class Test1 {

    static List<Student> studentList = new ArrayList<>();

    static {
        Student p1 = new Student();
        p1.setName("小米");
        p1.setAge(18);

        Student p2 = new Student();
        p2.setName("小米");
        p2.setAge(19);

        Student p3 = new Student();
        p3.setName("小华");
        p3.setAge(19);

        Student p4 = new Student();
        p4.setName("小华");
        p4.setAge(19);

        studentList.add(p1);
        studentList.add(p2);
        studentList.add(p3);
        studentList.add(p4);
    }

    public static void main(String[] args) {
        testRemoveJava();
        testRemove8();
        testRemove5();
    }

    static void testRemove8() {
        Set<Student> studentSet = new TreeSet<>(Comparator.comparing(o -> (o.getName())));
        studentSet.addAll(studentList);
        System.out.println("testRemove8()");
        new ArrayList<>(studentSet).forEach(System.out::println);
    }

    static void testRemoveJava() {
        System.out.println("testRemoveJava()");
        Set<Student> studentSet = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                //o1.getName().compareTo(o2.getName());   倒序
                //o2.getName().compareTo(o1.getName());   正序
                return o2.getName().compareTo(o1.getName());
            }
        });
        studentSet.addAll(studentList);
        //把set集合转成list
        ArrayList<Student> students = new ArrayList<>(studentSet);
        for (Student student : students) {
            System.out.println(student.toString());
        }
    }


    static void testRemove5() {
        Set<Student> studentSet = new TreeSet<>(Comparator.comparing(Student::getName));
        studentSet.addAll(studentList);
        System.out.println("testRemove5()");
        new ArrayList<>(studentSet).forEach(System.out::println);
    }
}

搞个自定义的去重

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值