Java基础学习 day_18 Java8新特性

Java8概述

在这里插入图片描述

Lambda表达式

在这里插入图片描述

//匿名内部类
Runnable runnable=new Runnable() {
    @Override
    public void run() {
        System.out.println("执行run方法...");
    }
};
//Lambda优化匿名内部类
Runnable runnable1= ()->{
    System.out.println("执行run方法...");
};
//Lambda表达式中只有一条语句,可以省略{};
Runnable runnable2= ()->System.out.println("执行run方法...");
//匿名内部类
Comparator<String> comparator = new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return o1.compareTo(o2);
    }
};
//Lambda优化匿名内部类
Comparator<String> comparator1 = (String o1, String o2) ->{
        return o1.compareTo(o2);
    };
//Lambda表达式中只有一条语句,可以省略{}和return;
Comparator<String> comparator2 = (o1,o2)->o1.compareTo(o2);
Comparator<String> comparator3 = String::compareTo;

在这里插入图片描述

函数式接口

在这里插入图片描述

常见的函数式接口

在这里插入图片描述

方法引用

在这里插入图片描述

//1.对象::实例方法
//(1)Lambda中只调用一个方法(2)调用的方法(println)的形式(参数和返回值)和接口方法一样
Consumer<String> consumer = s-> System.out.println(s);
consumer.accept("hah");
Consumer<String> consumer1= System.out::println;
consumer1.accept("oo");
//2.类::静态方法
//(1)Lambda中只调用一个方法,调用的方法(compare)的形式(参数和返回值)和接口方法一样
Comparator<Integer> comparator=(a,b)->Integer.compare(a, b);
Comparator<Integer> comparator1=Integer::compare;
System.out.println(comparator.compare(1, 3));
System.out.println(comparator1.compare(3, 2));
//3类::实例方法
//(1)Lambda中只调用一个方法(2)有一个参数作为Lambda中方法的调用者,其他还作为参数传递
Comparator<String> comparator2 =(o1,o2)->o1.compareTo(o2);
Comparator<String> comparator3=String::compareTo;
//3.2 类::实例方法
//(1)Lambda中只调用一个方法(2)有一个参数作为Lambda中方法的调用,如果没有其他参数,就不需要写了
Function<Employee,String> function1=e->e.getName();
Function<Employee,String> function2=Employee::getName;
//3.类::new
//(1)Lambda中只调用一个构造方法(2)构造方法的参数和接口的参数一样
Supplier<Employee> supplier = ()->new Employee();
Supplier<Employee> supplier1=Employee::new;
//如果想调用有参构造方法。可以自己写一个接口。
//(1)Lambda中只调用一个构造方法(2)构造方法的参数和接口的参数一样
MySupplier<Employee> supplier2 =(n,a)->new Employee(n,a);
MySupplier<Employee> supplier3=Employee::new;

自己写的接口

public interface MySupplier<T> {
    T apply(String name,int age);
}
//4.元素类型[]::new
//(1)Lambda中只创建数组,(2)参数作为数组的长度
Function<Integer,int[]> function=n->new int[n];
Function<Integer,int[]> function3=int[]::new;

Stream

流(Stream)与集合类似,集合中保存的是数据,而Stream中保存对集合或数组数据的操作
特点:
在这里插入图片描述
延迟执行,在调用终止操作的时候才执行

Stream不会在原对象上进行操作,比如排序,而是返回一个持有结果的Stream

创建流(Stream)

在这里插入图片描述

//1.collection的对象创建流
ArrayList<String> arrayList =new ArrayList<>();
arrayList.add("上海");
arrayList.add("下海");
arrayList.add("左海");
arrayList.add("右海");
arrayList.add("中海");
Stream<String> stream = arrayList.stream();
stream.forEach(System.out::println);
//2.Arrays创建流
IntStream stream1 = Arrays.stream(new int[]{2, 3, 1, 5, 4, 6});
//排序并遍历
stream1.sorted()
        .forEach(System.out::println);
//3.Stream创建流
System.out.println("-----------Stream创建流---------------");
Stream<Integer> stream2 = Stream.of(new Integer[]{22, 33, 11, 333, 222});
stream2.forEach(System.out::println);
//iterate()创建无限迭代流
System.out.println("--------------iterate创建流------------------");
Stream<Integer> iterate = Stream.iterate(1, i -> i + 2);
iterate.limit(10)
        .forEach(System.out::println);
//无限生成流generate()
System.out.println("------------------无限生成流-----------------");
Stream<Integer> generate = Stream.generate(()->new Random().nextInt(999));
generate.limit(3)
         .forEach(System.out::println);
//4 通过IntStream,LongStream,DoubleStream接口中的of,rang,rangClosed方法
System.out.println("-------------------of()--------------------");
IntStream intStream = IntStream.of(new int[]{3, 3, 2, 1});
intStream.distinct()
        .sorted()
        .limit(2)
        .forEach(System.out::println);
System.out.println("--------------------range(start,end)左闭右开-----------------------");
IntStream.range(1, 99)
        .forEach(System.out::println);
System.out.println("---------------------rangeClosed(start,end)左闭右闭------------------");
IntStream.rangeClosed(1, 99)
        .forEach(System.out::println);

中间操作、终止操作

1.中间操作:map():映射,parallel:并行流
2.终止操作:forEach():遍历,min():最小值,max():最大值,count():计算数目,reduce():归约,统计,collect():
在这里插入图片描述中间操作:

ArrayList<Employee> arrayList =new ArrayList<>();
arrayList.add(new Employee("张明轩",12,1900));
arrayList.add(new Employee("张小轩",12,19000));
arrayList.add(new Employee("张大轩",12,1800));
arrayList.add(new Employee("张轩",12,11119));
arrayList.add(new Employee("张轩",12,11119));
arrayList.add(new Employee("张轩",12,11119));
arrayList.add(new Employee("张暗",12,333339));
System.out.println("-----------遍历------------------");
arrayList.stream()
        .forEach(System.out::println);
System.out.println("------------filter-------------");
arrayList.stream()
        .filter(e->e.getName().endsWith("暗"))
        .forEach(System.out::println);
System.out.println("--------------sorted--------------");
arrayList.stream()
        .sorted((o1,o2)->Double.compare(o1.getSalary(),o2.getSalary()))
        .forEach(System.out::println);
System.out.println("-----------limit-------------------");
arrayList.stream()
        .limit(3)
        .forEach(System.out::println);
System.out.println("---------------skip---------------------");
arrayList.stream()
        .skip(3)
        .forEach(System.out::println);
//需重写hashCode()和equals()方法
System.out.println("-----------------distinct-----------------------");
arrayList.stream()
        .distinct()
        .forEach(System.out::println);
//map 映射
//获取所有人的名字
System.out.printlen("-----------------map映射---------------------")
arrayList.stream()
        .map(Employee::getName)
        .forEach(System.out::println);
//并行流 parallel
System.out.printlen("-----------------parallel并行流---------------------")
arrayList.stream()
        .parallel()
        .filter(e->e.getSalary()>11000)
        .sorted((o1,o2)->Double.compare(o1.getSalary(), o2.getSalary()))
        .distinct()
        .forEach(System.out::println);
Collectors工具类

Collectors.toList() 它将输入元素 List到一个新的 List 。
Collectors.toSet() 它将输入元素 List到一个新的 Set 。
Collectors.toMap() 它将输入元素 List到一个新的 Map 。

终止操作:
延迟执行,在调用终止操作的时候才执行

//forEach()遍历,就不在演示了
//min 最小值
Optional<Double> min = arrayList.stream()
        .map(e -> e.getSalary())
        .min((o1, o2) -> Double.compare(o1, o2));
System.out.println(min.get());
//最大值
Optional<Double> max = arrayList.stream()
        .map(e -> e.getSalary())
        .max((o1, o2) -> Double.compare(o1, o2));
System.out.println(max.get());
//count
long count = arrayList.stream( )
        .count();
System.out.println(count);
//reduce:归约,统计,计算工资和
Optional<Double> sum = arrayList.stream()
        .map(e -> e.getSalary())
        .reduce((x, y) -> x + y);
System.out.println(sum.get());
//collect收集
//收集所有的工资
//转换成List集合
List<Double> collect = arrayList.stream()
        .map(e -> e.getSalary())
        .collect(Collectors.toList());
System.out.println(collect.toString());
//计算平均工资
Double collect1 = arrayList.stream()
        .map(e -> e.getSalary())
        .collect(Collectors.averagingDouble(x -> x));
System.out.println(collect1);

新时间API(线程安全)

在这里插入图片描述
时间是不可变的,修改一次就会产生新的对象

LocalDateTime

//创建时间对象
LocalDateTime localDateTime = LocalDateTime.now();
//获取当前时间
System.out.println(localDateTime.toString());
//获取年
System.out.println(localDateTime.getYear());
//获取月
System.out.println(localDateTime.getMonth().getValue());
System.out.println(localDateTime.getMonthValue());
//获取日
System.out.println(localDateTime.getDayOfMonth());
//获取时
System.out.println(localDateTime.getHour());
//获取分
System.out.println(localDateTime.getMinute());
//获取秒
System.out.println(localDateTime.getSecond());
//昨天
LocalDateTime yesterday = localDateTime.minusDays(1);
//明天
LocalDateTime tomorrow = localDateTime.plusDays(1);
//设置时间
LocalDateTime time = LocalDateTime.of(2020, 8, 24, 10, 16);
//修改时间(修改到本月的10号)
LocalDateTime time1 = localDateTime.withDayOfMonth(10);
System.out.println(yesterday);
System.out.println(tomorrow);
System.out.println(time);
System.out.println(time1);

Instant(时间戳)

//创建instant:从1970.1.1 0:0:0,这个时间比我们晚8小时
Instant instant = Instant.now();
//获取秒
System.out.println(instant.getEpochSecond());
//获取毫秒
System.out.println(instant.toEpochMilli());
//昨天
Instant yesterday = instant.minusMillis(24*60*60*1000);
//明天
Instant tomorrow = instant.plus(1, ChronoUnit.DAYS);
System.out.println(instant);
System.out.println(yesterday);
System.out.println(tomorrow);

Date、Instant、LocalDateTime的转换

//Date->Instant->LocalDateTime
//创建Date
Date date = new Date();
System.out.println(date);
//Date 转换为 Instant
Instant instant = date.toInstant();
System.out.println(instant);
//时区ZoneId,ZoneId.systemDefault()当地时区
LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println(localDateTime.toString());
//LocalDateTime->Instant->Date
//创建LocalDateTime对象
LocalDateTime localDateTime1=LocalDateTime.now();
//转成Instant
Instant instant1 = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
//转成date
Date date1 = Date.from(instant1);
System.out.println(date1);

DateTimeFormat

//创建时间格式化器
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//把日期转成字符串
LocalDateTime localDateTime = LocalDateTime.now();
String format = dtf.format(localDateTime);
System.out.println(format);
//字符串转成日期
LocalDateTime time = LocalDateTime.parse("2020-08-12 15:20:19", dtf);
System.out.println(time.toString());
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值