Java8新特性(未完待续,不断更新)

java8四大核心内置函数

函数式接口名函数名函数描述式方法
Consumer消费性T -> voidvoid accept(T t)
Supplier供给型void -> TT get()
Function<T , R>函数型T -> RR apply(T t)
Predicate断言型T ->booleanboolean test(T t)

例子:

     @Test
    public void test1(){
        //消费型
        happy(1000.0 , (money) -> System.out.println("每次消费了"+money+"元"));
       //消费型
        happy(1000.0 , (money) -> System.out.println("每次消费了"+money+"元"));
        //供给型
        String supplyStr = sadnessSupplier( () -> "so so so much sadness!");
        System.out.println("has supplied:"+supplyStr);
        //函数型
        String funStrResult = funStr("123hellowpzhang" , (str) -> str.substring(3));
        System.out.println("has functioned:"+funStrResult);
        //断言型
        List<String> strList = Arrays.asList("hello" , "today" , "nice" , "!" , "ok");
        List<String> filterResult = new ArrayList<>();
        strList.forEach(str1 -> {
            if (filterStr(str1 , (perStr)-> perStr.length() > 3)){
                filterResult.add(str1);
            }
        });
        System.out.println(filterResult);
	}
	public void happy(Double money , Consumer<Double> consume){
        consume.accept(money);
    };
    public String sadnessSupplier(Supplier<String> supply){
        return supply.get();
    }
    public String funStr(String str , Function<String , String> myFun){
        return myFun.apply(str);
    }
    public boolean filterStr(String str , Predicate<String> myPre){
        return myPre.test(str);
    }

方法引用:是Lambda的另一种表现形式

三种方法引用使用规则
对象::实例方法Lambda体中 调用方法的参数列表、返回值类型 要与 该函数式接口中抽象方法的参数列表、返回值类型保持一致
类::实例方法参数列表中的第一个参数是实例方法的调用者,第二个参数是实例方法的参数
类::静态方法静态类名::方法名 ClassName :: method

例子:
对象::实例方法

//对象::实例方法 运用在Consumer对象::实例方法 运用在Consumer
 @Test
    public void test1(){
        PrintStream ps = System.out;
        Consumer<String> con = (str) -> ps.println(str);
        //使用方法引用简化后:
        Consumer<String> con2 = ps::print;
        con2.accept("12324");
    }
//对象::实例方法 运用在Supplier
    @Test
    public void supplierTest(){
        Emp emp = new Emp();
        Supplier<String> supplier = () -> emp.getName();
        //进一步简化
        Supplier<String> supplier2 = emp::getName;
        String supplierResult = supplier2.get();
        System.out.println(supplierResult);
    }
//对象::实例方法 运用在BiFunction(传入两个参数时)
	@Test
    public void functionTest() {
        BiFunction<String , Integer  , String> biFunTest = (fistStr , secondIndex) -> fistStr.substring(secondIndex);
        String result3 = biFunTest.apply("1997's wpzhang" ,7);
        System.out.println("result3:"+result3);
		//等同于
        BiFunction<String , Integer, String> biFunctionTest2 = String::substring;
        String biFunctionResult = biFunctionTest2.apply("1997's wpzhang" , 7);
        System.out.println("biFunctionResult:" + biFunctionResult);
	}

类::静态方法

 //类::静态方法 运用在Comparator
    @Test
    public void test3(){
        Comparator<Integer> com = (x, y) -> Integer.compare(x,y);
        //等同于
        Comparator<Integer> com2 = Integer::compare;
    }

类::实例方法

//类::实例方法 运用在BiPredicate
    @Test
    public void test4(){
        BiPredicate<String , String> biPredicate = (x,y) -> x.equals(y);
        boolean biPredicateResult = biPredicate.test("123" ,"123");
        System.out.println("biPredicateResult:"+biPredicateResult);
        //简化
        BiPredicate<String , String> biPredicate1 = String::equals;
        boolean biPredicateResult1 = biPredicate1.test("123" , "456");
        System.out.println("biPredicateResult1:"+biPredicateResult1);
    }

构造器引用

 	@Test
    public void test5(){
        //构造器引用默认调用的是无参构造器
        Supplier<Emp> emp = () -> new Emp();
        Emp result = emp.get();
        System.out.println("result"+result);
        //简化
        Supplier<Emp> emp2 = Emp::new;
        Emp result2 = emp2.get();
        System.out.println("result2"+result2);
        //调用一个参数的构造器
        Function<Integer , Emp> emp3 = Emp::new;
        Emp result3 = emp3.apply(23);
        System.out.println("result3:"+result3);
    }

数组引用

@Test
    public void test6(){
        Function<Integer , String[]> arrFun = (length) -> new String[length];
        String[] arr = arrFun.apply(10);
        System.out.println("result4:"+arr.length);
        //等同于
        Function<Integer , String[]> arrFun2 =String[]::new;
        String[] arr2 = arrFun2.apply(20);
        System.out.println("result5:"+arr2.length);
    }

Stream

step:

  • 创建流
  • 中间操作
  • 终止操作

创建流:

@Test
    public void test1(){
        //通过Collection系列集合创建流
        List<String> list = new ArrayList<>();
        Stream<String> stringStream = list.stream();
        //通过Arrays数组创建流
        String[] strArr = new String[10];
        Stream<String> streams = Arrays.stream(strArr);
        //通过stream中的静态方法of创建流
        Stream<String> strStream = Stream.of("11" , "22" , "33");
        //创建无限流
        Stream<Integer> noLimitStream = Stream.iterate(0,(x) -> x + 2);
        //终端流
        //noLimitStream.forEach(System.out::println);
        //终止流操作使得产生10个流
        noLimitStream.limit(10).forEach(System.out::println);
    }
    //生成的方式创建流
    @Test
    public void test2(){
        Stream<Double> streams = Stream.generate(() -> Math.random());
        streams.limit(5).forEach(System.out::println);
    }

中间操作

  • filter
  • limit
  • skip
  • distinct
  • map
  • flatMap
  • sorted排序
    -自然排序sorted()
    -定制排序sorted(comparator com)
    filter
	List<Emp> empList = Arrays.asList(
            new Emp("wpzhang" , 23 , "w" , 6666),
            new Emp("zl" , 24 , "w" , 8888),
            new Emp("zw" , 23 , "m" , 9999),
            new Emp("hch" , 27 , "m" , 10000),
            new Emp("wyy" , 28 , "m" , 15000),
            new Emp("wyy" , 28 , "m" , 15000)
    );
    //中间操作
    //filter
    @Test
    public void operate(){
        //中间操作  根本不会执行
        Stream<Emp> s = empList.stream()
                .filter((e) ->{
                    return  e.getAge() < 30;
                });
        //终止操作 有终止操作才会执行
        s.forEach(System.out::println);
    }

limit

   //中间操作limit
    @Test
    public void limitTest(){
        Stream<Emp> s = empList.stream()
                .filter((e) -> e.getSalary() > 8888)
                .limit(1);//一旦发现满足条件的一条数据以后,不再进行后续的操作,叫做短路
        s.forEach(System.out::println);
    }

skip

 	//中间操作skip :跳过结果的前三个,取第四个及以后的
    @Test
    public void skipTest(){
        empList.stream()
                .filter((e) -> e.getSalary() > 6666)
                .skip(3)
                .forEach(System.out::println);
    }

distinct

    //中间操作distinct:通过hashCode 和 equals方法实现的去重
    @Test
    public void distinctTest(){
        empList.stream()
                .distinct()
                .forEach(System.out::println);
    }

map

    //中间操作map映射
    @Test
    public void mapTest(){
        empList.stream()
                .map(Emp::getName)
                .forEach(System.out::println);
    }

flatMap

    @Test
    public void mapTest2(){
       List<String> strList = Arrays.asList("aa" , "bb" , "cc" ,"dd");
       //flatMap接受一个函数作为参数,将函数中每一个值作为一个流, 最后将流连接在一起返回
        //flatMap将每一个元素添加到流中
         strList.stream()
                .flatMap(BetweenOperation::filterCharacter)
                .forEach(System.out::println);//{a,a,a,b,b,b}
    }
    public static Stream<Character> filterCharacter(String str){
        List<Character> charList = new ArrayList<>();
        for (Character c : str.toCharArray()){
            charList.add(c);
        }
        return charList.stream();
    }

sort

    @Test
    public void sortTest(){
        //自然排序
        List<String> strList = Arrays.asList("a" , "b" , "z" ,"e");
        strList.stream()
                .sorted()
                .forEach(System.out::println);
        //定制排序
        empList.stream()
                .sorted((e1 , e2) ->{
                    if (e1.getAge() == e2.getAge()){
                        return e1.getName().compareTo(e2.getName());
                    }else{
                        return e1.getAge()-e2.getAge();
                    }
                }).forEach(System.out::println);
    }

终端操作

  • allMatch 是否匹配所有元素
  • anyMatch 是否至少匹配一个元素
  • noneMatch 检查是否没有匹配所有元素
  • findFirst 返回第一个元素
  • findAny 返回当前流中任意一个元素
  • count 返回当前流中元素的个数
  • max 返回当前流中的最大值
  • min 返回当前流中最小值
  • reduce() 可以将流中元素反复结合起来,返回一个Optional
  • collect 收集
public class TerminalOperation {
    List<Emp> empList = Arrays.asList(
            new Emp("wpzhang", 23, "w", 6666),
            new Emp("zl", 24, "w", 8888),
            new Emp("zw", 23, "m", 9999),
            new Emp("hch", 27, "m", 10000),
            new Emp("wyy", 28, "m", 15000),
            new Emp("wyy", 28, "m", 15000)
    );
    List<String> strList = Arrays.asList("aa", "bb", "cc", "bb", "ee", "bb", "dd");

    @Test
    public void test1() {
        //allMatch
        if (strList.stream().allMatch((str) -> !str.startsWith("!"))) {
            System.out.println("不以!”开头");
        }
        //anyMatch
        if (strList.stream().anyMatch((str) -> str.startsWith("a"))) {
            System.out.println("有一个以a开头的");
        }
        //noneMatch
        if (strList.stream().noneMatch((str) -> str.startsWith("g"))) {
            System.out.println("全部都不匹配!");
        }
        //findFirst返回第一个元素
        Optional<String> op = strList.stream().findFirst();
        String result = op.get();
        System.out.println("result:" + result);
        //findAny返回当前流中的任意一个元素
        //使用并行流查找任意元素
        Optional<String> result2 = strList.parallelStream().findAny();
        System.out.println("result2:"+result2.get());
        //count
        Long count = strList.stream().count();
        System.out.println("count:" + count);
        //max/min
        Optional<String> op2 = strList.stream().max((e1, e2) -> e1.compareTo(e2));
        System.out.println("result3:" + op2.get());
        //reduce 归约
        List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        Integer intResult = numList.stream()
                .reduce(0, (x, y) -> x + y);
        System.out.println("intList:" + intResult);
        Optional<Double> empOptional = empList.stream()
                .map(Emp::getSalary)//提取出工资
                .reduce(Double::sum);//类::静态方法
        System.out.println("empOptional:" + empOptional.get());
        //collect
        //收集所有名字
        List<String> nameList = empList.stream()
                .map(Emp::getName)
                .collect(Collectors.toList());
        System.out.println("nameList:" + nameList);
        //收集名字到Set中
        Set<String> set = empList.stream()
                                .map(Emp::getName)
                                .collect(Collectors.toSet());
        System.out.println("set:"+set);
        //收集名字到hashset中
        HashSet<String> nameSet = empList.stream()
                                        .map(Emp::getName)
                                        .collect(Collectors.toCollection(HashSet::new));
        System.out.println("nameSet:"+nameSet);
        //收集名字到LinkedHashSet中 存储有序且不重复
        LinkedHashSet<String> nameSortedSet = empList.stream()
                                                    .map(Emp::getName)
                                                    .collect(Collectors.toCollection(LinkedHashSet::new));
        System.out.println("LinkedHashSet:"+nameSortedSet);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值