欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 8 之 Optional类

程序员文章站 2022-05-01 09:18:39
...
在Java中,null代表一个不存在的对象,如果对它进行操作就会抛出java.lang.NullPointerException异常。NPE(NullPointerException)是调试程序最常见的异常。google一下有很多关于方法到底应该返回null还是new一个空对象的讨论。

类似于scala的scala.Option[T]、Haskell的Data.Maybe,Java 8 引入了java.util.Optional<T>。Opitonal就是一个元素的容器,Java8新添加的很多类或者方法的返回值都使用了Opitonal。Java5的话可以使用Google Guava的Optional来实现,Java8的Optional的接口跟Guava的Optional很相似。

// 创建Optional
String mayBeNull = null;
Optional<String> opt1 = Optional.of(" Hello, rensanning! ");
Optional<String> opt2 = Optional.ofNullable(mayBeNull);
Optional<String> opt3 = Optional.empty();


// ifPresent
opt1.ifPresent(System.out::println); // " Hello, rensanning! "
opt2.ifPresent(System.out::println);
opt3.ifPresent(System.out::println);


// isPresent
boolean b1 = opt1.isPresent();
boolean b2 = opt2.isPresent();
boolean b3 = opt3.isPresent();
System.out.println(b1 + "\t" + b2 + "\t" + b3); // true	false	false


// filter
opt1.filter(x -> x.contains("ren"))
	.ifPresent(System.out::println); // " Hello, rensanning! "
opt2.filter(x -> x.contains("ren"))
	.ifPresent(System.out::println);
opt3.filter(x -> x.contains("ren"))
	.ifPresent(System.out::println);


// map
opt1.map(String::trim)
	.ifPresent(System.out::println); // "Hello, rensanning!"


// flatMap
Optional<String> lastName = Optional.of("last");
Optional<String> firstName = Optional.of("first");
Optional<String> fullName = 
		  lastName.flatMap(ln -> firstName.map(fn -> String.join(" ", ln, fn)));
System.out.println(fullName.get()); // "last first"


Optional<Integer> len = opt1.map(String::length);

// get
System.out.println(len.get()); // 20
try {
	System.out.println(opt2.get());
} catch (Exception e) {
	// java.util.NoSuchElementException
	e.printStackTrace();
}


// orElse/orElseGet/orElseThrow
int len1 = opt1.map(String::length).orElse(-1);
int len2 = opt2.map(String::length).orElse(-1);
int len3 = opt3.map(String::length).orElseGet(() ->  5*40);
System.out.println(len1 + "\t" + len2 + "\t" + len3); // 20	-1	200
try {
	opt3.filter(s -> !s.isEmpty())
		.map(s -> s.charAt(0))
		.orElseThrow(IllegalArgumentException::new);
} catch (Exception e) {
	// java.lang.IllegalArgumentException
	e.printStackTrace();
}


// Optional -> List
List<String> list1 = opt1.map(Collections::singletonList)
   	 				     .orElse(Collections.emptyList());
System.out.println(list1.get(0));// " Hello, rensanning! "


// OptionalInt/OptionalLong/OptionalDouble
OptionalInt optionalInt = OptionalInt.of(90);
System.out.println(optionalInt.getAsInt()); // 90		
OptionalLong optionalLong = OptionalLong.of(999_999_999_999_999_999L);
System.out.println(optionalLong.getAsLong()); // 999999999999999999		
OptionalDouble optionalDouble = OptionalDouble.of(56.000009);
System.out.println(optionalDouble.getAsDouble()); // 56.000009


参考:
http://www.importnew.com/6675.html
http://blog.informatech.cr/2013/04/10/java-optional-objects/
相关标签: Java 8