'Filtering a list of list of object with another list in Java 8
I am new to Java 8 and trying to filter a list of list comparing with another list but unable to do.
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);
}
}
Child list to compare with:
List<BigDecimal> sidList = new ArrayList();
sidList.add(100012);
So in this case the result should only return
List<ProductDetail> which has pd1 object in it.
So far i have done this, but it doesn't work.
List<ProductDetail> listOutput =
pdList.stream()
.filter(e -> sidList.contains(e.getSerialCodes().stream().filter(f->f.getSerialId())))
.collect(Collectors.toList());
Solution 1:[1]
Stream operations should not modify or mutate any external state. So I would suggest using this :
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());
Solution 2:[2]
You can do something like this.
List<ProductDetail> listOutput = new ArrayList<>();
pdList.forEach(e -> {
e.serialcodes.forEach(f -> {
if (sidList.contains(BigDecimal.valueOf(f.getSerialId()))) {
listOutput.add(e);
}
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sajit Gupta |
| Solution 2 | Harshita Sethi |
