Reputation: 471
I have an XML schema and generated corresponding POJO classes from JAXB. The xml sample is provided at the end.
I have a list which holds ship orders. I want to collect all items if the price of the item is more than 100. I was able to do it using java 7 but thought of doing the same in java 8 using streams. I tried but couldn't achieve the same. Could some one please help me how to write the code?
List<Shiporder> shiporders = new ArrayList<>();
shiporders.add(getShipOrder("src/allinone/order1.xml"));
shiporders.add(getShipOrder("src/allinone/order2.xml"));
<shiporder orderid="Order_1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="shiporder.xsd">
<orderperson>Suman pandey</orderperson>
<shipto>
<name>Suman pandey</name>
<address>BTM layout</address>
<city>Bangalore</city>
<country>India</country>
</shipto>
<item>
<title>Samsung S2</title>
<note>Special Edition</note>
<quantity>1</quantity>
<price>100.90</price>
</item>
<item>
<title>Oppo</title>
<quantity>4</quantity>
<price>20.90</price>
</item>
</shiporder>
Upvotes: 1
Views: 967
Reputation: 30686
How about this?
List<Item> items = shiporders.stream()
.map(Shiporder::getItems)
.flatMap(List::stream)
.filter(it -> it.price > 100)
.collect(Collectors.toList());
Upvotes: 4
Reputation: 203
shiporders.stream()
.filter(new Predicate<Shiporder>(){
public boolean test(Shiporder shiporder) {
return <boolean condition on shiporder>;
}
}).collect(Collectors.asList);
or you can substitute the anonymous inner class with a lambda in the form
shiporders.stream()
.filter(shiporder -> <boolean condition on shiporder>)
.collect(Collectors.asList);
Upvotes: 1