java 将两个List对象合并并去重

第一种整个对象进行去重处理

import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.Stream;

List<OrderAppointmentSales> orderAppointmentSales = obcOrderAppointmentSalesService.getOrderAppointmentSalesList(syncTime);
List<OrderAppointmentSales> orderAppointmentSales2 = obcOrderAppointmentSalesService.getOrderAppointmentSalesListByTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS").format(sas.getUpdateTime()));
//将数据list对象合并去重 使用Stream来帮我们完成操作
List<OrderAppointmentSales> ords = Stream.of(orderAppointmentSales, orderAppointmentSales2)
                        .flatMap(Collection::stream)
                        .distinct()
                        .collect(Collectors.toList());

第二种针对指定字段进行去重

List<ShipmentHeader> ords = new ArrayList<>();
ords.addAll(listByWms1);
ords.addAll(listByWms2);

List<ShipmentHeader> studentList = new ArrayList<>(ords.stream()
        .collect(Collectors.toMap(ShipmentHeader::getId, Function.identity(), (oldValue, newValue) -> newValue))
        .values());

Collectors.toMap需要使用三个参数的版本,前两个参数一个是keyMapper函数一个是valueMapper函数的,第三个参数BinaryOperator函数接口。BinaryOperator函数接收两个参数,一个oldValue,一个newValue。用于当key重复时的数据处理

posted @ 2022-08-04 14:51  darling331  阅读(5798)  评论(0编辑  收藏  举报