My First Post      My Facebook Profile      My MeOnShow Profile      W3LC Facebook Page      Learners Consortium Group      Job Portal      Shopping @Yeyhi.com

Pages










Monday, August 31, 2020

Replace For Loop with Foreach in Java: PMD ruleset="Best Practices" rule="ForLoopCanBeForeach"


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20

private boolean isEligible(final BookedItems bookedItem) {
if (ALLOWED_TYPES.stream().anyMatch(cartItem.getProductType()::equalsIgnoreCase)) {
      List<HomeProduct> listHomeProducts = cartItem.getProducts().getHomeProducts();
      for (int counter = 0; counter < listHomeProducts.size(); counter++) {
        List<CartTicketInfo> listCartTicketInfo = listHomeProducts.get(counter).getCartTicketInfoList();
        for (int counter2 = 0; counter2 < listCartTicketInfo.size(); counter2++) {
          if (listCartTicketInfo.get(counter2).getIsUnusedTicket())  {
            return true;
          }
        }
      }
    }
    return false;
  }
}

Easy modification for this code is as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
private boolean isEligibleWaiverRedemptionItem(final BookedItems bookedItem) {
    if (ALLOWED_TYPES.stream().anyMatch(cartItem.getProductType()::equalsIgnoreCase)) {
      for (HomeProduct homeProduct : cartItem.getProducts().getHomeProducts()) {
for (CartTicketInfo cartTicketInfo : homeProduct.getCartTicketInfoList()) { if (CartTicketInfo.getIsUnusedTicket()) { return true; } } } } return false; } }