本地变量类型判断
var str = "hello Java11";
System.out.println(str);//hello Java11
var list = new ArrayList<String>();
list.add("hello Java11");
System.out.println(list.get(0));//hello Java11
可以使用var,而不用写具体的类型
字符串新特性
- isBlank()
// 判断空白字符串
String str = " ";
System.out.println(str.isBlank()); //true
- strip()
// 去首尾的空格
String str = " Java ";
System.out.println(str.strip()); //"Java"
- stripTrailing()
// 去尾的空格
String str = " Java ";
System.out.println(str.stripTrailing()); //" Java"
- stripLeading()
// 去首的空格
String str = " Java ";
System.out.println(str.stripLeading()); //" Java"
- repeat()
//复制字符串
String str = "Java";
System.out.println(str.repeat(4)); //JavaJavaJavaJava
- lines().count()
String str = "Java\nJava\nJava";
System.out.println(str.lines().count()); //3
集合新特性
####自JDK9开始(List/Set/Map)都添加了of和copyOf方法,用来创建不可变集合
var list = List.of("Java", "C#", "Ruby");
var copy = List.copyOf(list);
System.out.println(list == copy); // true
使用 of 和 copyOf 创建的集合为不可变集合,不能进行添加、删除、替换、排序等操作,不然会报 java.lang.UnsupportedOperationException 异常。
至于为什么会这样,点到of源码
static <E> List<E> of(E e1, E e2, E e3) {
return new ImmutableCollections.ListN<>(e1, e2, e3);
}
static final class ListN<E> extends AbstractImmutableList<E>
implements Serializable
ListN是继承了AbstractImmutableList这个抽象类
再看看这个抽象类部分源码
static abstract class AbstractImmutableList<E> extends AbstractImmutableCollection<E>
implements List<E>, RandomAccess {
// all mutating methods throw UnsupportedOperationException
@Override public void add(int index, E element) { throw uoe(); }
@Override public boolean addAll(int index, Collection<? extends E> c) { throw uoe(); }
@Override public E remove(int index) { throw uoe(); }
@Override public void replaceAll(UnaryOperator<E> operator) { throw uoe(); }
@Override public E set(int index, E element) { throw uoe(); }
@Override public void sort(Comparator<? super E> c) { throw uoe(); }
这样就很明显了,不能去add或者remove等操作,即不可变。
copyOf同理
static <E> List<E> copyOf(Collection<? extends E> coll) {
return ImmutableCollections.listCopy(coll);
}
static <E> List<E> listCopy(Collection<? extends E> coll) {
if (coll instanceof AbstractImmutableList && coll.getClass() != SubList.class) {
return (List<E>)coll;
} else {
return (List<E>)List.of(coll.toArray());
}
}
static final class SubList<E> extends AbstractImmutableList<E> implements RandomAccess
判断下是不是定长的,是就直接返回,不是就用of去创建一个定长的。
Stream流新特性
Stream作为Jdk8的新特性,Jdk9开始对Steam新增了4个新方法
- takeWhile(),条件成立开始计算
var list = List.of(1,2,3);
var result = list.stream().takeWhile(n -> n <= 2).collect(Collectors.toList());
System.out.println(result);//[1,2]
- dropWhile(),条件不成立开始计算
var list = List.of(1,2,3);
var result = list.stream().dropWhile(n -> n <= 2).collect(Collectors.toList());
System.out.println(result);//[3]
- Stream.ofNullalble()
Long result = Stream.ofNullable(null).count();
System.out.println(result);//0
- iterate,之前使用需要用limit去截断,现在可以改成
Stream<Integer> iterate = Stream.iterate(1, i -> i <= 5, i -> i + 1);iterate.forEach(System.out::println); //1,2,3,4,5
Optional表达式新特性
可以在第一个Optional为空的时候来一个or,在or里面继续一个Optional
Optional.ofNullable(null)
.or(()->Optional.of("Hello World Java11")).ifPresent(System.out::println);
增加对stream支持
var list = Optional.of("HelloJava11").stream().collect(Collectors.toList());
list.forEach(System.out::println);
orElseThrow可以不传参,在JDK8这种写法是会报错的
Optional.of("1").orElseThrow();
/**
* If a value is present, returns the value, otherwise throws
* {@code NoSuchElementException}.
*
* @return the non-{@code null} value described by this {@code Optional}
* @throws NoSuchElementException if no value is present
* @since 10
*/
public T orElseThrow() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
查看源码可以发现在JDK10的时候已经增加了无参的方法
InputStream新特性
transferTo()可以直接把输入流写入到输入流中
var classLoader = ClassLoader.getSystemClassLoader();
var inputStream = classLoader.getResourceAsStream("test.txt");
var text2 = File.createTempFile("test2", "txt");
try (var outputStream = new FileOutputStream(text2)) {
inputStream.transferTo(outputStream);
System.out.println(outputStream);
}
HttpClient新特性
var request = HttpRequest.newBuilder()
.uri(URI.create("https://www.baidu.com"))
.GET()
.build();
var client = HttpClient.newHttpClient();
// 同步
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
// 异步
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
这是Java9的API,该API已经支持同步和异步,而在Java11中已经成为正式可用状态,可以在java.net中找到