I am looking for a more efficient way of accomplishing the result of the following code pre java 8 (this is on an app hosted on Google App Engine which does not yet support Java 8)
List<Order> orders = getOrders();
List<LineItem> lineItems = new ArrayList<>();
for (final Order order : orders) {
for (final LineItem lineItem : order.getItems()) {
lineItems.add(lineItem);
}
}
Is there a more efficient means of accomplishing this without needing to use Java 8 functionality? Possibly using Guava
You can make it more efficient by avoiding the resize operation required by
ArrayList
when it hits the backing array size, and that's by calculating the size required before inserting.Although this would scan
orders
twice, it can perform better ifgetItems
are big and the backing-array need to be copied several times during resize.