Java8新特性

Lambda表达式

特殊的匿名内部类,语法更简洁
Lambda表达式允许把函数作为一个方法的参数(函数作为方法参数传递),将代码像数据一样传递

package La;

import java.lang.invoke.LambdaConversionException;

public class Demo1 {
    public static void main(String[] args) {
        //匿名内如雷
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                System.out.println("子线程执行了");
            }
        };
        Thread thread=new Thread(runnable);
        thread.start();
        Runnable runnable1=()-> System.out.println("子线程执行了");
        new Thread(runnable1).start();
        new Thread(()-> System.out.println("子线程执行了")).start();
    }
}

基本语法

<函数式接口> < 变量名> =(参数1,参数2.。)->{方法体};

注意事项

  • 形参列表的的数据类型自动推断
  • 形参列表为空只保留()
  • 如果形参只有一个()可以省略,只需要参数的名称即可
  • 如果执行语句只有一家,且无返回值,{}可省略,若有返回值,则若想省去{},则必须同时省略return,且执行语句也只有一句
  • Lambda不会生成一个单独的内部类文件

函数式接口

如果一个接口只有一个抽象方法,则该接口就是函数式接口,函数式接口可以使用Lambda表达式,会被匹配到这个抽象方法上。

  • @FunctionalInterface注解检测接口是否符合函数式接口
package La;
@FunctionalInterface
public interface Usb {
    void service();

}

package La;

public class Demo2 {
    public static void main(String[] args) {
        Usb usb=new Usb() {
            @Override
            public void service() {
                System.out.println("鼠标工作");
            }
        };
        Usb fun=()->{
            System.out.println("Lamdba方法运行");
        };
        run(fun);
        run(usb);
    }
private static void run(Usb usb){
    usb.service();
}
}

常见的函数式接口

在这里插入图片描述

package La;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class Demo3 {
    public static void main(String[] args) {
        happy((t)-> System.out.println("聚餐消费"+t),1000);
        int [] arrs=getNumbs(()->new Random().nextInt(100),5);
        System.out.println(Arrays.toString(arrs));;
       String s =hadlerString(sd -> sd.toUpperCase(),"eeee");
        System.out.println(s);
        List<String> names=new ArrayList<>();
        names.add("张三");
        names.add("李四");

        List<String> result= fileterName(s1 -> s1.startsWith("张"),names);
        System.out.println(result.toString());
    }

    public static void happy(Consumer<Double> consumer, double money){
        consumer.accept(money);
    }
    public static int[] getNumbs(Supplier<Integer> integerSupplier,int count){
        int [] arr=new int[count];
        for (int i = 0; i <count ; i++) {
            arr[i]=integerSupplier.get();
        }
        return arr;
    }
    public static String hadlerString(Function<String ,String> function,String str){
        return function.apply(str);
    }
    public static List<String> fileterName(Predicate <String> predicate,List<String> list){
        List<String> strings=new ArrayList<String>();
        for (String string :list
             ) {
            if(predicate.test(string)){
                strings.add(string);
            }

        }
        return strings;
    }

}

方法引用

是Lambda表达式的一种简写形式。如果Lambda表达式方法体中只是调用一个特定的已经存在的方法,则可以使用方法引用

常见形式

在这里插入图片描述

Stream

流中保存对集合或数组数据的操作,和集合类似,但集合中保存的是数据

特点:

  • Stream自身不会存储元素
  • 不会改变源对象,会返回一个持有结果的新的Stream
  • Stream 操作是延迟执行的,这意味着他们会等到需要结果的时候才执行

使用步骤

  • 创建一个流
  • 中间操作
    • 在一个或多个步骤中,将初始Stream 转化到另一个Stream的中间操作
  • 终止操作
    • 使用一个终止操作来产生一个结果,该操作会强制它之前的延迟操作立即执行,在这之后,该Stream就不能使用了

创建Stream

通过Collection对象的stream()串行或parallelStream()并行流方法
Arrays类的steam()方法
通过Stream接口的of()\iterate()\generate()方法
通过IntStream、LongStream、DoubleStream接口中的of、range、rangeClosed方法

package La;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Demo5 {
    public static void main(String[] args) {
        //Collection中的stream()和parallelStream()方法
        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("apple");
        arrayList.add("小米");
        Stream<String> stringStream=arrayList.stream();
        stringStream.forEach(System.out::println);
        Stream<String> stringStream1=arrayList.parallelStream();
        stringStream1.forEach(System.out::println);
        //Arrays的Stream方法
        String [] arr={"aaa","bbb","ccc"};
        Stream<String> stringStream2= Arrays.stream(arr);
        stringStream2.forEach(System.out::println);
        //Stream的of方法 iterate generate
        Stream<Integer> stream=Stream.of(10,20,30);
        stream.forEach(System.out::println);
        Stream<Integer> integerStream=Stream.iterate(0,x->x+2);
        integerStream.limit(10).forEach(System.out::println);
        System.out.println("================");
        Stream stream1=Stream.generate(()->new Random().nextInt(100));
        stream1.limit(10).forEach(System.out::println);
        System.out.println("===========");
        //Int、Long、DoubleStream的of、range、rangeClosed
        IntStream intStream=IntStream.of(100,200,300);
        intStream.forEach(System.out::println);
        IntStream intStream1=IntStream.rangeClosed(0,50);
        intStream1.forEach(System.out::println);

    }
}

中间操作

  • fileter、limit、skip、distinct、sorted
  • map
  • parallel
package com.qf.chap18_1;

import java.util.ArrayList;

/**
 * Stream的使用
 * (1)中间操作
 * @author wgy
 *
 */
public class Demo6 {
	public static void main(String[] args) {
		ArrayList<Employee> list=new ArrayList<>();
		list.add(new Employee("小王", 15000));
		list.add(new Employee("小张", 12000));
		list.add(new Employee("小李", 18000));
		list.add(new Employee("小孙", 20000));
		list.add(new Employee("小刘", 25000));
		//list.add(new Employee("小刘", 25000));
		//中间操作1 filter过滤   2 limit 限制  3 skip 跳过  4 distinct 去掉重复  5 sorted排序
		//filter过滤
		System.out.println("------filter-------");
		list.stream()
			.filter(e->e.getMoney()>15000)
			.forEach(System.out::println);
		//limit限制
		System.out.println("----limit------");
		list.stream()
			.limit(2)
			.forEach(System.out::println);
		//skip跳过
		System.out.println("-----skip------");
		list.stream()
			.skip(2)
			.forEach(System.out::println);
		System.out.println("------distinct--------");
		//distinct去重复
		list.stream()
			.distinct()
			.forEach(System.out::println);
		
		System.out.println("---------sorted---------");
		//sorted排序
		list.stream()
			.sorted((e1,e2)->Double.compare(e1.getMoney(), e2.getMoney()))
			.forEach(System.out::println);
				
		//中间操作2 map
		System.out.println("---------map--------");
		list.stream()
			.map(e->e.getName())
			.forEach(System.out::println);
		//中间操作3 parallel 采用多线程 效率高
		System.out.println("---------map--------");
		list.parallelStream()
			.forEach(System.out::println);
			
		
	}
}

终止操作

  • forEach、min、max、count
  • reduce、collect

新时间API

DateTimeFormatter 线程安全
DateTimeFormatter.ofPattern(“yyyyMMdd”);
LocalDate("",DateTimeFormatter.ofPattern(“yyyyMMdd”));日期
LocalTime 时间
LocalDateTime 日期时间 用法一样

now
of
plusDays 新的LocalDayTime 增加
minusMonths减少

//1创建本地时间
		LocalDateTime localDateTime=LocalDateTime.now();
		//LocalDateTime localDateTime2=LocalDateTime.of(year, month, dayOfMonth, hour, minute)
		System.out.println(localDateTime);
		System.out.println(localDateTime.getYear());
		System.out.println(localDateTime.getMonthValue());
		System.out.println(localDateTime.getDayOfMonth());
		
		//2添加两天
		LocalDateTime localDateTime2 = localDateTime.plusDays(2);
		System.out.println(localDateTime2);
		
		//3减少一个月
		LocalDateTime localDateTime3 = localDateTime.minusMonths(1);
		System.out.println(localDateTime3);

Instant

public class Demo3 {
	public static void main(String[] args) {
		//1创建Instant:时间戳
		Instant instant=Instant.now();
		System.out.println(instant.toString());
		System.out.println(instant.toEpochMilli());
		System.out.println(System.currentTimeMillis());
		//2添加减少时间
		
		Instant instant2 = instant.plusSeconds(10);
		
		System.out.println(Duration.between(instant, instant2).toMillis());
		
		//3ZoneId
		Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
		for (String string : availableZoneIds) {
			System.out.println(string);
		}
		
		System.out.println(ZoneId.systemDefault().toString());
		
		//1 Date --->Instant---->LocalDateTime
		System.out.println("-------------Date --->Instant---->LocalDateTime-----------");
		Date date=new Date();
		Instant instant3 = date.toInstant();
		System.out.println(instant3);
		
		LocalDateTime localDateTime = LocalDateTime.ofInstant(instant3, ZoneId.systemDefault());
		System.out.println(localDateTime);
		
		//1 LocalDateTime --->Instant---->Date
		System.out.println("-------------LocalDateTime --->Instant---->Date-----------");
	
		Instant instant4 = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
		System.out.println(instant4);
		Date from = Date.from(instant4);
		System.out.println(from);
		
	}
}
package com.qf.chap18_2;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * DateTimeFormatter类的使用
 * @author wgy
 *
 */
public class Demo4 {
	public static void main(String[] args) {
		//创建DateTimeFormatter
		DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
		//(1)把时间格式化成字符串
		String format = dtf.format(LocalDateTime.now());
		System.out.println(format);
		//(2)把字符串解析成时间
		LocalDateTime localDateTime = LocalDateTime.parse("2020/03/10 10:20:35", dtf);
		System.out.println(localDateTime);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值