More efficient method of aggregating items into su

2019-07-27 01:47发布

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

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-27 02:27
 List<Order> orders = getOrders();
 List<LineItem> lineItems = new ArrayList<>();

 for (final Order order : orders) {
     lineItems.addAll(order.getItems());
 }
查看更多
倾城 Initia
3楼-- · 2019-07-27 02:30

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.

查看更多
登录 后发表回答