java入门-JDK1.8新特性
Java 8 (又称为 jdk 1.8) 是 Java 语言开发的一个主要版本。 Oracle 公司于 2014 年 3 月 18 日发布 Java 8 ,它支持函数式编程,新的 JavaScript 引擎,新的日期 API,新的Stream API 等。
1、Lambda 表达式
Lambda 允许把函数作为一个方法的参数(函数作为参数传递到方法中)。
@Test
public void lambaTest(){
//Lambda 表达式 排序方法
Comparator<Integer> cpt2 = (x,y) -> Integer.compare(x, y);
TreeSet<Integer> ts = new TreeSet<Integer>(cpt2);
ts.add(4);
ts.add(3);
ts.add(1);
ts.add(5);
ts.add(0);
ts.forEach(l -> {
System.out.print(l+" ");
});
}
结果:
0 1 3 4 5
2、方法
1、函数式接口
@Test
public void funTest(){
System.out.println(changeNum(4L,(x) -> x - 1));
Function<String,String> fun = (x) -> x+ "1";
System.out.println(fun.apply("a"));
}
/**
* Function<T,R> 函数式接口
* @param num
* @param fun
* @return
*/
public Long changeNum(Long num, Function<Long, Long> fun){
return fun.apply(num);
}
结果:
3
a1
2、供给型接口
@Test
public void test2(){
String value = getValue(() -> "hello");
System.out.println(value);
}
/**
* Supplier<T> 供给型接口
* @param sup
* @return
*/
public String getValue(Supplier<String> sup){
return sup.get();
}
结果:
hello
3、消费型接口
@Test
public void test(){
changeStr("hello",(str) -> System.out.println(str));
}
/**
* Consumer<T> 消费型接口
* @param str
* @param con
*/
public void changeStr(String str, Consumer<String> con){
con.accept(str);
}
结果:
hello
3、Stream API
新添加的Stream API(java.util.stream) 把真正的函数式编程风格引入到Java中
@Test
public void streamTest(){
List<Integer> ll = new ArrayList<Integer>();
ll.add(1);
ll.add(2);
ll.add(3);
ll.add(4);
ll.add(5);
ll.add(6);
ll.forEach(l -> {
System.out.print(l);
});
System.out.println("===========");
//过滤访问
ll.stream().filter(l -> l > 1).limit(4).forEach(l -> {
System.out.print(l);
});
System.out.println("===========");
//遍历计算
ll.stream().filter(l -> l > 1).map(l -> l+2).forEach(l -> {
System.out.print(l);
});
System.out.println("===========");
//过滤生成新的集合
List<Integer> l2 = ll.stream().filter(l -> l > 4).collect(Collectors.toList());
l2.forEach(l -> {
System.out.print(l);
});
System.out.println("===========");
//统计,求和
System.out.print(l2.stream().mapToInt(Integer::valueOf).sum());
}
结果:
123456===========
2345===========
45678===========
56===========
11
求和、最大值、最小值、过滤等
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class StreamDemo {
static class User{
User(Integer id,String name ,Integer age,String address){
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
User(){
}
private Integer id;
private String name;
private Integer age;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public static void main(String[] args) {
User user1 = new User(1,"jim",23,"北京");
User user2 = new User(2,"tom",24,"武汉");
User user3 = new User(3,"echo",25,"深圳");
User user4 = new User(4,"jerry",26,"上海");
User user5 = new User(5,"bob",27,"北京");
/**
* 查找和匹配
* allMatch-检查是否匹配所有元素
* anyMatch-检查是否至少匹配一个元素
* noneMatch-检查是否没有匹配所有元素
* findFirst-返回第一个元素
* findAny-返回当前流中的任意元素
* count-返回流中元素的总个数
* max-返回流中最大值
* min-返回流中最小值
*/
//数据库、集合 : 存数据的
// Stream:计算和处理数据交给 Stream
List<User> users = Arrays.asList(user1, user2, user3, user4, user5);
/* users.stream()
.filter(u->{return u.getId()%2 == 0;})
.filter(u->{return u.getAge() > 24;})
.map(u->{return u.getName().toUpperCase();})
.sorted((u1,u2)->{return u2.compareTo(u1);})
.limit(1)
.forEach(System.out::println);*/
/* IntSummaryStatistics is = users.stream()
.mapToInt(u->{return u.getAge();})
.summaryStatistics();
System.out.println(is.getSum());*/
List<String> infos = users.stream().map(u -> u.getName()).collect(Collectors.toList());
Optional<String> reduced = infos.stream()
.sorted()
.reduce((s1, s2) -> s1 + "#" + s2);
reduced.ifPresent(System.out::println);
//取年龄最大和最小的
Optional<User> max = users.stream().max((e1,e2) -> Integer.compare(e1.getAge(), e2.getAge()));
Optional<User> min = users.stream().min((e1,e2) -> Integer.compare(e1.getAge(), e2.getAge()));
System.out.println("最大值:"+max.get().getAge()+",最小值:"+min.get().getAge());
}
}
结果:
bob#echo#jerry#jim#tom
最大值:27,最小值:23
4、Date Time API
加强对日期与时间的处理。
@Test
public void test(){
// 从默认时区的系统时钟获取当前的日期时间。不用考虑时区差
LocalDateTime date = LocalDateTime.now();
//2018-07-15T14:22:39.759
System.out.println(date);
System.out.println(date.getYear());
System.out.println(date.getMonthValue());
System.out.println(date.getDayOfMonth());
System.out.println(date.getHour());
System.out.println(date.getMinute());
System.out.println(date.getSecond());
System.out.println(date.getNano());
// 手动创建一个LocalDateTime实例
LocalDateTime date2 = LocalDateTime.of(2017, 12, 17, 9, 31, 31, 31);
System.out.println(date2);
// 进行加操作,得到新的日期实例
LocalDateTime date3 = date2.plusDays(12);
System.out.println(date3);
// 进行减操作,得到新的日期实例
LocalDateTime date4 = date3.minusYears(2);
System.out.println(date4);
}
结果:
2021-08-01T17:02:43.835
2021
8
1
17
2
43
835000000
2017-12-17T09:31:31.000000031
2017-12-29T09:31:31.000000031
2015-12-29T09:31:31.000000031
5、CompletableFuture
1、 runAsync 和 supplyAsync方法
CompletableFuture 提供了四个静态方法来创建一个异步操作。
public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
/**
* 没有返回值
* @throws Exception
*/
@Test
public void runAsync() throws Exception {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("runAsync方法");
});
future.get();
}
结果:
runAsync方法
/**
* 有返回值
* @throws Exception
*/
@Test
public void supplyAsync() throws Exception {
CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {
return 100L;
});
long value = future.get();
System.out.println("value = "+value);
}
结果:
value = 100
@Test
public void complementFun()throws Exception {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("runAsync方法");
});
future.whenComplete(new BiConsumer<Void, Throwable>() {
@Override
public void accept(Void t, Throwable action) {
System.out.println("执行完成!");
}
});
future.exceptionally(new Function<Throwable, Void>() {
@Override
public Void apply(Throwable t) {
System.out.println("执行失败!"+t.getMessage());
return null;
}
});
CompletableFuture<Long> future2 = CompletableFuture.supplyAsync(() -> {
return 100L;
}).thenApply(new Function<Long, Long>() {
@Override
public Long apply(Long t) {
long result = t*5;
System.out.println("result2="+result);
return result;
}
});
long result = future2.get();
System.out.println(result);
}
结果:
runAsync方法
执行完成!
result2=500
500
jdk1.8新特性简单介绍到这里,想要了解更多,可以查看下面地址:
jdk1.8新特性:https://blog.csdn.net/wwwzhouzy/article/details/118056027
CompletableFuture异步编程:https://blog.csdn.net/wwwzhouzy/article/details/118056216