StreamAPI取两个List中一方的差集,并按所需属性转换为新的List

这篇博客演示了如何使用Java Stream API从一个列表中过滤出不在另一个列表中的元素。主要涉及数据处理、集合操作和流API的使用,包括map、filter和collect方法,用于找出新列表`newL`中不包含在旧列表`old`中的ID以及对应的mainId。
摘要由CSDN通过智能技术生成

直接上代码

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


public class Test {

    public static void main(String[] args) {
        Temp temp1 = new Temp(11L, 1, "11111");
        Temp temp2 = new Temp(22L, 2, "22222");
        Temp temp3 = new Temp(22L, 2, "22222");
        Temp temp4 = new Temp(33L, 3, "33333");
        List<Temp> old = new ArrayList<>();
        old.add(temp1);
        old.add(temp2);
        List<Temp> newL = new ArrayList<>();
        newL.add(temp3);
        newL.add(temp4);
        // 取newL中不包含old的id
        List<Integer> collectId = newL.stream().map(Temp::getId).filter(id -> !old.stream().map(Temp::getId)
                .collect(Collectors.toList()).contains(id)).collect(Collectors.toList());
        // 取newL中不包含old的id,并转换为新的mainId(或对象,或其他属性)List
        List<Long> collectMainId = newL.stream().filter(it -> !old.stream().map(Temp::getId).collect(Collectors.toList())
                .contains(it.getId())).map(Temp::getMainId).collect(Collectors.toList());
        System.out.println(collectId); // 3
        System.out.println(collectMainId); //33L
    }


}

@Data
class Temp {
    Long mainId;
    Integer id;
    String item;

    public Temp(Long mainId, Integer id, String item) {
        this.mainId = mainId;
        this.id = id;
        this.item = item;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值