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
List<Order> orders = getOrders();
List<LineItem> lineItems = new ArrayList<>();
for (final Order order : orders) {
lineItems.addAll(order.getItems());
}
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.
int size = 0;
for (Order order : orders) {
size += order.getItems().size();
}
List<LineItem> lineItems = new ArrayList<>(size);
for (Order order : orders) {
lineItems.addAll(order.getItems());
}
Although this would scan orders
twice, it can perform better if getItems
are big and the backing-array need to be copied several times during resize.