List,Set 和 Map 接口中,新的工厂方法JEP269可以创建这些集合的不可变实例,代码便得更容易阅读,包括Collection下的List/Set, Map
// JAVA8 写法
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list = Collections.unmodifiableList(list);
System.out.println(list);
// JAVA9 写法
List<String> list9 = List.of("A", "B", "C");
System.out.println(list9);
java8中引进的Optional类用来减少程序空指针异常,并使得Stream API更鲁棒。jdk9中为Optional增加了新方法
ifPresent(Consumer action): 如果值存在, 执行action表达式,否则什么也不做ifPresent(Consumer<? super T> action)
// ifPresent(Consumer super T> action)
Consumer<String> action = (value)-> System.out.println(value) ;
Optional<String> optionalH = Optional.of("hello word");
optionalH.ifPresent(action);
ifPresentOrElse(Consumer action, Runnable emptyAction): 和ifPresent相似,有值执行action,没有值执行emptyAction // ifPresentOrElse(Consumer action, Runnable emptyAction)
Optional<String> optionalE =Optional.empty();
Runnable emptyRun = ()-> System.out.println("空值,默认内容");
optionalE.ifPresentOrElse(action, emptyRun);
or(Supplier supplier): 如果值存在,返回 Optional 指定的值,否则返回一个预设的值。 Optional<String> optional1 = Optional.of("Andy");
Supplier<Optional<String>> supplierString = () -> Optional.of("Not Present");
optional1 = optional1.or( supplierString);
optional1.ifPresent( x -> System.out.println("Value: " + x));
optional1 = Optional.empty();
optional1 = optional1.or( supplierString);
optional1.ifPresent( x -> System.out.println("Value: " + x));
stream(): 将 Optional 转为一个 Stream,如果该 Optional 中包含值,那么就返回包含这个值的 Stream,否则返回一个空的 Stream(Stream.empty())。(这个功能太棒了!)public Stream<T> stream()
// java 8
List<Optional<String>> list = Arrays.asList (
Optional.empty(),
Optional.of("A"),
Optional.empty(),
Optional.of("B"));
List<String> filteredList = list.stream()
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
.collect(Collectors.toList());
// java 9
List<String> filteredListJava9 = list.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
System.out.println(filteredList);
System.out.println(filteredListJava9);
Java 9 改进的 Stream API 添加了一些便利的方法,使流处理更容易,并使用收集器编写复杂的查询
takeWhile(Predicate)
有序返回流中的尽可能多的元素,直到断言不为真。
default Stream<T> takeWhile(Predicate<? super T> predicate)
// takeWhile 方法
Stream.of("1","2","3","","4","5")
.takeWhile(s->!s.isEmpty())
.forEach(System.out::println);
// 打印结果 123
dropWhile(Predicate)
default Stream<T> dropWhile(Predicate<? super T> predicate)
dropWhile 方法和 takeWhile 作用相似,使用一个断言作为参数,直到断言不为真,返回这之后的stream
// dropWhile 方法
Stream.of("a","b","c","","e","f")
.dropWhile(s-> !s.isEmpty())
.forEach(System.out::println);
// 打印结果 ef
ofNullable 方法
static <T> Stream<T> ofNullable(T t)
ofNullable 方法可以预防 NullPointerExceptions 异常, 可以通过检查流来避免 null 值。
如果指定元素为非 null,则获取一个元素并生成单个元素流,元素为 null 则返回一个空流。
// ofNullable
long count = Stream.ofNullable( "张").count();
System.out.println(count);
count = Stream.ofNullable(null).count();
System.out.println(count);
static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)
方法允许使用初始种子值创建顺序(可能是无限)流,并迭代应用指定的下一个方法。 当指定的 hasNext 的 predicate 返回 false 时,迭代停止
// iterator
IntStream.iterate(3, x -> x < 10, x -> x + 3).forEach(System.out::println);
// 运行结果
3
6
9
在 Java 8之前,接口可以有常量变量和抽象方法,java8接口引入了默认方法和静态方法,Java 9 不仅像 Java 8 一样支持接口默认方法,同时还支持私有方法、私有静态方法
public class InterfacePrivateMethod {
public static void main(String[] args) {
Logging.LogMysql logMysql = new Logging.LogMysql();
logMysql.logInfo("hello private method");
}
}
interface Logging {
final class LogMysql implements Logging {
}
private void log(String message, String prefix) {
getConnection();
System.out.println("Log Message : " + prefix);
closeConnection();
}
private static void getConnection() {
System.out.println("Open Database connection");
}
private static void closeConnection() {
System.out.println("Close Database connection");
}
default void logInfo(String message) {
log(message, "INFO");
}
default void logDebug(String message) {
log(message, "DEBUG");
}
}
// 程序运行结果
Open Database connection
Log Message : INFO
Close Database connection
try-with-resources 是 JDK 7 中一个新的异常处理机制,它能够很容易地关闭在 try-catch 语句块中使用的资源。
所谓的资源(resource)是指在程序完成后,必须关闭的对象。try-with-resources 语句确保了每个资源在语句结束时关闭。所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源
try-with-resources 声明在 JDK 9 已得到改进。如果你已经有一个资源是 final 或等效于 final 变量,您可以在 try-with-resources 语句中使用该变量,而无需在 try-with-resources 语句中声明一个新变量。
public static void main(String[] args) throws IOException {
System.out.println(readData7("test7"));
System.out.println(readData9("test9"));
}
// java 7
static String readData7(String message) throws IOException {
Reader inputString = new StringReader(message);
BufferedReader br = new BufferedReader(inputString);
try (BufferedReader br1 = br) {
return br1.readLine();
}
}
// java9
static String readData9(String message) throws IOException {
Reader inputString = new StringReader(message);
BufferedReader br = new BufferedReader(inputString);
try (br) {
return br.readLine();
}
}