Last active
June 17, 2018 01:02
-
-
Save sirius2k/2e8a2cacc7d35f7168c1cff2cd7cf043 to your computer and use it in GitHub Desktop.
Java Optional usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Before | |
public Member getMemberIfExceedsBasePrice(Order order, long basePrice) { | |
if (order != null && order.getTotalPrice() > basePrice) { | |
return order.getMember(); | |
} | |
} | |
// After | |
public Optional<Member> getMemberIfExceedsBasePrice(Order order, long basePrice) { | |
return Optional.ofNullable(order) | |
.filter(order -> order.getTotalPrice() > basePrice) | |
.map(Order::getMember); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Optional<Product> optionalProduct = Optional.ofNullable(products.get("nonExists")); | |
optionalProduct.ifPresent(product -> { | |
System.out.println("productName : " + product.getName()); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Before | |
public String getCityOfMemberFromOrder(Order order) { | |
if (order!=null) { | |
Member member = order.getMember(); | |
if (member!=null) { | |
Address address = member.getAddress(); | |
if (order.getMember().getAddress()!=null) { | |
return address.getCity(); | |
} | |
} | |
} | |
return "Seoul"; | |
} | |
// After | |
public String getCityOfMemberFromOrder(Order order) { | |
return Optional.ofNullable(order) | |
.map(Order::getMember) | |
.map(Member::getAddress) | |
.map(Address::getCity) | |
.orElse("Seoul"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Before | |
public long getSpecificProductPrice(Map<Product> products) { | |
Product product = products.get("nonExists"); | |
if (products!=null) { | |
return product.getPrice(); | |
} else { | |
return 0L; | |
} | |
} | |
// After | |
public long getSpecificProductPrice(Map<Product> products) { | |
Optional<Product> optionalProduct = Optional.ofNullable(products.get("nonExists")); | |
return optionalProduct.map(Product::getPrice).orElse(0L); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment