Optional使用方法

/**
 * 
 */
package com.gewb.stream;

import java.util.Optional;

/**
 * @author Bingo.Ge
 * @date 2020年6月26日
 */
public class OptionalUsage {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		/*
		 * Optional dishOptional = Optional.of(new Dish()); dishOptional.get();
		 */
		
		Optional dishOptional2 = Optional.ofNullable(new Dish("Bingo.Ge"));
		/*
		 * dishOptional2.orElseGet(Dish::new); 
		 * dishOptional2.orElse(new Dish());
		 * dishOptional2.orElseThrow(RuntimeException::new);
		 * dishOptional2.orElseThrow(()->new RuntimeException("Not have reference"));
		 */
		
		/*
		 * Dish dish = dishOptional2.filter(i->i.getName()==null).get();
		 * System.out.println(dish);
		 */
		
		/*
		 * Optional map = dishOptional2.map(i->i.getName());
		 * System.out.println(map.orElse("empty value")); // 是否有值
		 * System.out.println(map.isPresent()); map.ifPresent(System.out::println);
		 */
		
		System.out.println(getDishName(null));
		System.out.println(getDishNameByOptional(null));
		
	}

	private static String getDishName(Dish dish) {
		if(dish == null) {
			return "unknown";
		}
		
		return dish.getName();
	}
	
	private static String getDishNameByOptional(Dish dish) {
		return Optional.ofNullable(dish).map(Dish::getName).orElse("unknown");
	}
	
}

 

你可能感兴趣的:(jdk8)