list集合里的对象按某个字段去重

  • Post author:
  • Post category:其他


List<User> lists = 从某处得来的集合;
lists = lists.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<(Comparator.comparing(User::getXxx))), ArrayList::new));

针对于多个字段的去重,我们可以进行拼接去重:

List<Map<String, String>> arrayList = list.stream().
collect(Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(o -> o.get(“name”) +:+ o.get(“address”) +:+ o.get(“sex”)))), ArrayList::new));

从list集合中抽取getId转为新的集合:

List<NatCustomers> natCustomersList = natCustomersService.queryListByPage(0,1000);
List<Integer> customerIds = natCustomersList.stream().map(NatCustomers::getId).collect(Collectors.toList());

把list集合按getCustomerId字段进行分组:

List<ConsumptionStatistics>  consumptionStatistics = natServicesService.getConsumptionStatistics(paramMap);
Map<Integer, List<ConsumptionStatistics>> collect = consumptionStatistics.stream().collect(Collectors.groupingBy(ConsumptionStatistics::getCustomerId));



版权声明:本文为weixin_43244841原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。