List集合去重,排序,对象,equals,

2019-12-11  本文已影响0人  一只弹窗仔

List元素为基本数据类型,去重

public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(3);
        list.add(3);
        list.add(1);
        list.add(2);
        list.add(6);
        list.add(2);
        list.add(5);
        System.out.println("list:" + list);
        List<Integer> list1 = new ArrayList<>(new HashSet<>(list));
        System.out.println("HashSet去重:"+list1);
        List<Integer> list2 = new ArrayList<>(new LinkedHashSet<>(list));
        System.out.println("LinkedHashSet去重:"+list2);
        List list3 = list.stream().distinct().collect(Collectors.toList());
        System.out.println("stream去重:"+list3);
    }
image

// 使用lambad表达式去重

List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("A",10));
        studentList.add(new Student("A",11));
        studentList.add(new Student("B",12));
        studentList.add(new Student("C",13));
        studentList.add(new Student("D",13));
        studentList.add(new Student("D",13));
        System.out.println(JSON.toJSONString(studentList));
        List<Student> list = studentList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparing(Student::getName))), ArrayList::new));
        System.out.println("根据name去重:"+JSON.toJSONString(list));
        List<Student> list1 = studentList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparing(s -> s.getName() + ";" + s.getAge()))), ArrayList::new)
        );
        System.out.println("根据name和age去重:"+JSON.toJSONString(list1));

image

List元素为对象事时去重,需要重写对象的equals和hashCode方法

@Override
    public boolean equals(Object obj) {
        if (obj == null){
            return false;
        }
        if (this == obj){
            return true;
        }
        if (!(obj instanceof Student)){
            return false;
        }
        Student s = (Student) obj;
        return this.name.equals(s.getName()) && this.age.equals(s.getAge());

    }

    @Override
    public int hashCode() {
        return Objects.hash(name,age);
    }
image

去重后LinkedHashSet保持原来顺序,HashSet无序;

//排序

对象实现Comparable,然后重写compareTo方法;

@Override
    public int compareTo(Student o) {
        return this.age-o.age;
    }
image
上一篇下一篇

猜你喜欢

热点阅读