1. 程式人生 > >List stream 物件 屬性去重

List stream 物件 屬性去重

單值去重不寫了,記錄物件去重

隨手一個物件:

@Data
@AllArgsConstructor
public class Milk {
    private Integer key;
    private String value;
}

 

操作:

package com.yus.util;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

public class main {
    public static void main(String[] args) {
        Milk milk0=new Milk(0,"a");
        Milk milk1=new Milk(1,"b");
        Milk milk2=new Milk(0,"c");
        List<Milk> list=new ArrayList<>();
        list.add(milk0);
        list.add(milk1);
        list.add(milk2);
        //去重
        List<Milk> uniqueMilk = list.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparing(n->n.getKey()))),ArrayList::new)
        );

        for (Milk m:uniqueMilk) {
            System.out.println(m.toString());
        }

    }
}

 

操作底層是set,檢視,collection...一堆東西,還是有點意思的,不記錄了,有興趣可深入