Java List集合根據某欄位去重
阿新 • • 發佈:2021-12-20
去重方法
單個欄位為條件去重
/** * 單欄位去重 * @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 ) ); }