2015-05-09 216 views
3

我有這應該解析XML文件中的類,像這樣:如何避免嵌套for-each循環?

<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); 
    } 
} 

客戶,訂單和位置類已經從XSD模式自動生成,我認爲改變它們並不好。

我到底做錯了什麼?我怎樣才能避免這些嵌套循環?

謝謝。

+0

我想象應該有一些圖書館可以讓你選擇DOM內的元素。但是,我從來沒有用Java做過,所以不能指出任何東西。 – mcraen

回答

4

我會建議提取一些方法:

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; 
} 

做同樣的事情的順序和位置環,給方法的描述,足以名,並確保它們返回正確的價值觀,你會得到一個不錯的,乾淨的代碼。這些仍然是嵌套循環,但至少當你看到它們時你的眼睛不會受到傷害。