Java_Optional

1 篇文章 0 订阅
package cn.jxb;

import java.util.Optional;

import org.junit.Test;

/**	
 *	Description:  
 * 	@author: b_z  2020年8月16日  下午11:49:34
 * 		jdk8增加java.util.Optional
 *		Optional可以看成是一个迷你型的容器,用来装一个对象的容器
 *		因为java语言有一个异常经常被诟病,NullPointException
 *		为了解决空指针异常
 *
 *		当一个方法设计形参时,或者返回结果时,都可以使用Optional类
 *		
 *		Optional的使用:
 *			如何创建一个Optional类
 *				static <T> Optional <T> empty()
 *				
 *				static <T> Optional <T> of(T value)
 *					创建一个非空的Optional对象
 *
 *				static <T> Optional <T> ofNullable(T value)
 *					创建一个可能为空,可能非空的对象
 *		
 *		如何取出包装的值?
 *				T get()	对应of方法,因为要求必须非空
 *				T orElse(T other)		对应的为foNullable
 *					如果容器中就非空就返回容器中的对象
 *					如果容器中为空就用备胎来代替
 *				T orElseGet(Supllier<? extend T> other)		对应的为foNullable
 *					如果容器非空就使用容器中的对象,为空就是用Supplier来代替
 *				<X extends Throwable> T orElseThrow(Suppplier<? extends X> exceptionSupplier)
 *					如果容器中非空就返回容器中的对象,如果容器中为空,就抛出指定的异常
 *				
 *		其他方法:
 *			Optional<T> filter(Predicate<? super T> predicate)
 *			<U> Optional <U> map(Function<? super T,? extends U> mapper)
 *			boolean isPresent()
 *			void ifPresent(Consumer<? super T> consumer)
 *				
 */
public class TestOptional {
	@Test
	public void test1() {
		//返回结果就是这么一个对象
		Optional<Object> empty = Optional.empty();
		//等价于原来的null,创建一个空的Optional对象,相当于里面包装了一个null
		//以前很多放发return null;现在很多方法使用return  Optional.empty();来代替
		System.out.println(empty);//Optional.empty
	}
	@Test
	public void test2() {
		Optional<String> of = Optional.of("北京");//Optional[北京]
		System.out.println(of);
	}
	@Test
	public void test3() {
		Optional<String> of = Optional.of("null");//错误必须非空
		System.out.println(of);
	}
	@Test
	public void test4() {
		Optional<String> of = Optional.of("北京");//Optional[北京]
		String string = of.get();
		System.out.println(string);
	}
	@Test
	public void test5() {
		Optional<String> of = Optional.ofNullable(null);
		//为空使用备胎来代替
		String string = of.orElse("上海");
		System.out.println(string);
	}
	@Test
	public void test6() {
		Optional<String> of = Optional.ofNullable("北京");
		/*
		 * 		supllier<T> :	T get()
		 * 		如果容器中非空,就返回容器中的结果
		 * 		如果容器为空,就使用supplier这个供给型接口
		 */
		
		String string = of.orElseGet(()->"上海");
		System.out.println(string);
	}
	@Test
	public void test7() {
		//为空抛出指定的异常
		Optional<String> of = Optional.ofNullable(null);
		/*
		 * 		supllier<T> :	T get()
		 * 		如果容器中非空,就返回容器中的结果
		 * 		如果容器为空,就抛出Supplier提供的异常
		 */		
		String string = of.orElseThrow((()->new RuntimeException("用户信息错误")));
		System.out.println(string);
	}
	
}

package cn.jxb;

/**	
 *	Description:  
 * 	@author: b_z  2020年8月17日  上午9:05:25
 *
 */
public class Employee {
	private int id;
	private String name;
	private double salary;
	
	/**
	 * 
	 */
	public Employee() {
		super();
	}
	/**
	 * @param id
	 * @param name
	 * @param salary
	 */
	public Employee(int id, String name, double salary) {
		super();
		this.id = id;
		this.name = name;
		this.salary = salary;
	}
	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}
	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	/**
	 * @return the salary
	 */
	public double getSalary() {
		return salary;
	}
	/**
	 * @param salary the salary to set
	 */
	public void setSalary(double salary) {
		this.salary = salary;
	}
	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
	}
}

package cn.jxb;

import java.util.ArrayList;
import java.util.Optional;

/**	
 *	Description:  
 * 	@author: b_z  2020年8月17日  上午9:07:26
 *
 */
public class EmployeeService {
	private ArrayList<Employee> list;
	public EmployeeService() {
		//初始化集合,添加模拟数据
		list = new ArrayList<Employee>();
		list.add(new Employee(1, "张三", 10000));
		list.add(new Employee(2, "李四", 11000));
		list.add(new Employee(3, "王五", 12000));
		list.add(new Employee(4, "赵六", 13000));
	}
	
	//可以根据id查询员工对象的方法
	public Employee getById(int id) {
		for (Employee employee : list) {
			if(id == employee.getId()) {
				return employee;
			}
		}
		return null;
	}
	//可以根据id查询员工对象的方法
	public Optional<Employee> getByIdOpt(int id) {
		for (Employee employee : list) {
			if(id == employee.getId()) {
				return Optional.of(employee);
			}
		}
		return Optional.empty();
	}
}

package cn.jxb;

import java.util.Optional;

import org.junit.Test;

/**	
 *	Description:  
 * 	@author: b_z  2020年8月17日  上午9:14:40
 *
 */
public class TestEmployeeService {
	@Test
	public void test1() {
		//查询编号为3的员工打印信息
		//查询之前需要对象
		EmployeeService es = new EmployeeService();
		Employee emp = es.getById(3);
		System.out.println(emp.getName());
	}
	
	//避免空指针异常的方法
	@Test
	public void test2() {
		EmployeeService es = new EmployeeService();
		Optional<Employee> opt = es.getByIdOpt(3);
		Employee emp = opt.orElse(new Employee());
		System.out.println(emp.getName());
	}
	
	//查询编号为2的员工,如果薪资小于15000就涨薪资
	//避免空指针异常的方法
	@Test
	public void test3() {
		EmployeeService es = new EmployeeService();
		Optional<Employee> opt = es.getByIdOpt(2);
		opt.map(t -> {
			if(t.getSalary() < 15000) {
				t.setSalary(15000);
			}
			return t;
		});
		Employee employee = opt.get();
		System.out.println(employee);
	}
	@Test
	public void test4() {
		EmployeeService es = new EmployeeService();
		Optional<Employee> opt = es.getByIdOpt(2);
		//小于12000的留下
		opt = opt.filter(t -> t.getSalary()<12000);
		System.out.println(opt);
		//判断是否存在再进行操作
		if(opt.isPresent()) {
			Employee emp = opt.map(t -> {t.setSalary(10000); return t;}).get();
			System.out.println(emp);
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值