1. 程式人生 > 其它 >Java List集合根據某欄位去重

Java List集合根據某欄位去重

去重方法

單個欄位為條件去重

/**
     * 單欄位去重
     * @param jackpotList1 新集合
     * @param jackpotList 需要去重的集合
     * @return
     */
    private List<Jackpot> distinctList1(List<Jackpot> jackpotList1, List<Jackpot> jackpotList) {
        jackpotList1.addAll(jackpotList);
        return jackpotList1.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Jackpot::getPrizeId))),ArrayList::new
                )
        );
    }

多個欄位為條件去重

/**
     * 多欄位去重
     * @param jackpotList1 新集合
     * @param jackpotList 需要去重的集合
     * @return
     */
    private List<Jackpot> distinctList(List<Jackpot> jackpotList1, List<Jackpot> jackpotList) {
        jackpotList1.addAll(jackpotList);
        return jackpotList1.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(jackpot -> jackpot.getMyOrderId() + ";" + jackpot.getPrizeId()))),ArrayList::new
                )
        );
    }
無論風雨,和自己一決勝負吧