我有一个应该解析 XML 文件的类,如下所示:
<customers>
...
<customer>
<id>123456</id>
<name>Mike</name>
<orders>
...
<order>
<id>233658</id>
<positions>
...
<position>
<id>12345</id>
<price>10.0</price>
<count>5</count>
</position>
...
</positions>
</order>
...
</orders>
</customer>
<customers>
我将使用 JAXB 解码它,然后处理结果对象以获得统计信息(例如最大订单量、总订单量等)
在这种情况下,使用 3 级 foreach 循环是一种不好的做法吗?
public void getStatistics() {
for (Customer customer: this.customers.getCustomer()) {
BigDecimal customerTotalAmount = new BigDecimal(0);
for (Order order : customer.getOrders().getOrder()) {
BigDecimal orderAmount = new BigDecimal(0);
for (Position position : order.getPositions().getPosition()) {
orderAmount = orderAmount.add( position.getPrice().multiply(new BigDecimal(position.getCount())) );
}
customerTotalAmount = customerTotalAmount.add(orderAmount);
this.totalOrders++;
}
this.totalAmount = this.totalAmount.add(customerTotalAmount);
}
}
Customer、Order 和 Position 类已经从 XSD 模式自动生成,我认为更改它们并不好。
我做错了什么?我怎样才能避免那些嵌套循环?
谢谢。
最佳答案
我会推荐提取一些方法:
public void getStatistics() {
for (Customer customer: this.customers.getCustomer()) {
BigDecimal customerTotalAmount = processCustomer(customer);
this.totalAmount = this.totalAmount.add(customerTotalAmount);
}
}
private void processCustomer(Customer customer){
BigDecimal customerTotalAmount = new BigDecimal(0);
for (Order order : customer.getOrders().getOrder()) {
BigDecimal orderAmount = new BigDecimal(0);
for (Position position : order.getPositions().getPosition()) {
orderAmount = orderAmount.add( position.getPrice().multiply(new BigDecimal(position.getCount())) );
}
customerTotalAmount = customerTotalAmount.add(orderAmount);
this.totalOrders++;
}
return customerTotalAmount;
}
对 Order 和 Position 循环执行相同的操作,为方法提供足够描述性的名称并确保它们返回正确的值,然后您将获得一个漂亮、干净的代码。这些仍然是嵌套循环,但至少当你看到它们时你的眼睛不会受伤。
关于java - 如何避免嵌套的 for-each 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30134686/