使用Java 8中的另一个列表过滤对象列表的列表

时间:2018-03-25 06:11:59

标签: java list collections filter java-stream

我是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);

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

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

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

2 个答案:

答案 0 :(得分:1)

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

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());

答案 1 :(得分:0)

你可以这样做。

List<ProductDetail> listOutput = new ArrayList<>();

pdList.forEach(e -> {
    e.serialcodes.forEach(f -> {
        if (sidList.contains(BigDecimal.valueOf(f.getSerialId()))) {
            listOutput.add(e);
        }
    });
});