gpt4 book ai didi

java - 在 Java 8 中用另一个列表过滤对象列表的列表

转载 作者:行者123 更新时间:2023-12-02 11:28:06 25 4
gpt4 key购买 nike

我是 Java 8 的新手,尝试过滤列表的列表与另一个列表进行比较,但无法做到。

ProductDetail.class

public class ProductDetail {
long productNo;
String productStr;
long productCount;
List<SerialCode> serialCodes;
}

SerialCode.class
public class SerialCode {
int serialId;
String serialName;
}


public class Main {
public Main() {
// TODO Auto-generated constructor stub
List<ProductDetail> pdList = new ArrayList();

List<SerialCode> sdList = new ArrayList();
SerialCode sd = new SerialCode();

sd.setSerialName("sname1");

sdList.add(sd);

List<SerialCode> sdList1 = new ArrayList();
SerialCode sd1 = new SerialCode();
sd1.setSerialId(100013);
sd1.setSerialName("sname2");

sdList1.add(sd1);

ProductDetail pd1 = new ProductDetail();
pd1.setProductNo(1234);
pd1.setProductStr("STR1");
pd1.setProductCount(20);
pd1.setSerialCodes(sdList);

ProductDetail pd2 = new ProductDetail();
pd2.setProductNo(1255);
pd2.setProductStr("STR2");
pd2.setProductCount(40);
pd2.setSerialCodes(sdList1);

pdList.add(pd1);
pdList.add(pd2);
}
}

要比较的子列表:

List<BigDecimal> sidList = new ArrayList();
sidList.add(100012);

所以在这种情况下结果应该只返回 List<ProductDetail>其中有 pd1 对象。

到目前为止我已经做到了这一点,但它不起作用。

List<ProductDetail> listOutput =
pdList.stream()
.filter(e -> sidList.contains(e.getSerialCodes().stream().filter(f->f.getSerialId())))
.collect(Collectors.toList());

最佳答案

流操作不应修改或改变任何外部状态。所以我建议使用这个:

final List<ProductDetail> list = pdList.stream()
.filter(p -> p.serialCodes.stream()
.map(s -> BigDecimal.valueOf(s.serialId))
.anyMatch(x -> sidList.stream().anyMatch(b -> b.equals(x))))
.collect(Collectors.toList());

关于java - 在 Java 8 中用另一个列表过滤对象列表的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49473050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com