Skip to content

Instantly share code, notes, and snippets.

@sirius2k
Last active June 17, 2018 01:02
Show Gist options
  • Save sirius2k/2e8a2cacc7d35f7168c1cff2cd7cf043 to your computer and use it in GitHub Desktop.
Save sirius2k/2e8a2cacc7d35f7168c1cff2cd7cf043 to your computer and use it in GitHub Desktop.
Java Optional usage
// 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);
}
Optional<Product> optionalProduct = Optional.ofNullable(products.get("nonExists"));
optionalProduct.ifPresent(product -> {
System.out.println("productName : " + product.getName());
};
// 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");
}
// 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