Advertisement
Guest User

Example 2 (corrected)

a guest
Jan 22nd, 2016
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.05 KB | None | 0 0
  1. /*
  2. Example 2 from the Jan. 2016 "Programmez" article (fair use), with some minor formatting changes and some variable names translated to English:
  3.  
  4. Old code:
  5. */
  6.  
  7. PaymentCard mainCardToReturn = null;
  8. for(final PaymentCard card: paymentCards) {
  9.   if(!card.isExpired() && !card.isDefault()
  10.     && mainCardToReturn == null ||
  11.       mainCardToReturn.creationDate().before(card.getCreationDate())) {
  12.     mainCardToReturn = card;
  13.   }
  14. }
  15.  
  16. /*
  17. New Java-8 stream Code:
  18. */
  19. PaymentCard mainCardToReturn = paymentCards.stream()
  20.   .filter(card -> !card.isExpired() && !card.isDefault())
  21.   .min(Comparator.comparing(card -> card.getCreationDate().getTime()))
  22.   .orElse(null);
  23.  
  24. /*
  25. It's difficult to follow in the "Programmez" article, but apparently the benchmark for this change actually showed a performance improvement (executed in Contiperf 100 times, the old code took 30 ns and the new Java-8 stream code took 14 ns).  
  26.  
  27. What I do not understand is why payment cards flagged as "default" are filtered out, but that's the business logic they preserved.  
  28. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement