java8新特性-----------------01-02-03-04-05-06-07-08-09-10-11-12-13

书:

代码:

   

讲了用java8之前的一些写法。

最后讲了箭头表达式:

List<Apple> lambdaResult = findApple(list, apple -> apple.getColor().equals("green"));

        System.out.println(lambdaResult);

        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
        }).start();


        new Thread(() -> System.out.println(Thread.currentThread().getName())).start();


        Thread.currentThread().join();

java8一个接口只有一个方法就是一个Function。default方法和静态方法除外。箭头表达式就是new一个对象,重写了里面唯一的方法。

--------------------------------------------------------------------------------------01-------------20191230-----------------------------------------------------

讲了如何查看虚拟机:---

java8一个接口只有一个方法就是一个Function。default方法和静态方法除外。

  代码:

----------------------------------------------------------------------------------02--------------20191231--------------------------------------------------------

lambda表达式的经典的写法:

List<Apple> lambdaResult = findApple(list, apple -> apple.getColor().equals("green"));//加入一个filter这个自己就写好了 注意左面是参数  有面是接口的实现的方法
new Thread(() -> System.out.println(Thread.currentThread().getName())).start();
 Comparator<Apple> bywcolorlambda = (o1,o2)->o1.getColor().compareTo(o2.getColor());

什么是lambda表达式的语:lambda可以很清晰的展示匿名内部类。

什么时候在哪里如何使用:

execute around pattern:

Functional interface:

Method reference:

Type interface:

COmposing lambda:

代码:

一个知识点,什么时候用return,什么时候不用return。

用return就是带花括号的时候:

不用就是不带花括号的时候是可以推导出来的。

一个知识点,lambda表达式的写法:

注意lambda表达式主要是为这些服务的:

知识点:

通过上面的我们总结下lambda表达式的语法:

箭头表达式和new事一样的。在参数里面的都是enw。

lambda表达式是其他的基础。

关于::    :https://blog.csdn.net/kegaofei/article/details/80582356

Java 8 中我们可以通过 `::` 关键字来访问类的构造方法,对象方法,静态方法。

-------------------------------------------------------------03------------------20200101-------------------------------------------------------------------------

lambda表达式的用法:

里面有default方法和static的都可以认为是可以进行函数式编程的:https://www.jianshu.com/p/7c685a6197bb

主要是说下lambda表达式在哪里用到的:

 代码:

应用:Predicate Consumer Function Supplier

   

知识点:

predicate:

public class PredicateUse {
    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 150), new Apple("yellow", 
   120),
                new Apple("green", 170), new Apple("red", 170));
        System.out.println(filter(list,(apple)->apple.getColor().equals("green")));

        List<Apple> list2 = Arrays.asList(new Apple("green", 150), new Apple("yellow", 
   120),
                new Apple("green", 170), new Apple("red", 170));
        System.out.println(filterByWeight(list,w -> w==150L));

        List<Apple> list3 = Arrays.asList(new Apple("green", 150), new Apple("yellow", 
   120),
                new Apple("green", 170), new Apple("red", 170));
        System.out.println(filterByBiPredicate(list,(c,w) -> 
    c.equals("green")&&w>=150L));
    }

    public static List<Apple> filterByWeight(List<Apple> source,LongPredicate predicate){
        List<Apple> resault = new ArrayList<>();
        for(Apple a:source){
            if(predicate.test(a.getWeight())){
                resault.add(a);
            }
        }
        return resault;
    }

    public static List<Apple> filterByBiPredicate(List<Apple> source,BiPredicate<String,Long> predicate){
        List<Apple> resault = new ArrayList<>();
        for(Apple a:source){
            if(predicate.test(a.getColor(),a.getWeight())){
                resault.add(a);
            }
        }
        return resault;
    }


// 这个方法就是predicate替换了之前的那个接口

    private static List<Apple> filter(List<Apple> source,Predicate<Apple> predicate){
        List<Apple> resault = new ArrayList<>();
        for(Apple a:source){
            if(predicate.test(a)){
               resault.add(a);
            }
        }
        return resault;
    }


}

总结:predicate实际上就是Apple那个类的接口,传入的是lambda表达式也就是test的实现,返回值是true或者false。接口里面唯一的方法是test。test的返回值是true和false。

Consumer:

public class ConsumerUser {
    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 150), new Apple("yellow", 120),
                new Apple("green", 170), new Apple("red", 170));
        simpletestonsumer(list,a->System.out.println(a));
        simpletestonsumerBi(list,"dddddd",(a,c)->System.out.println(c+a.getColor()));
    }

    private static void simpletestonsumerBi(List<Apple> source, String c,BiConsumer<Apple,String> consumer){
        List<Apple> resault = new ArrayList<>();
        for(Apple a:source){
            consumer.accept(a,c);
        }
    }

    private static void simpletestonsumer(List<Apple> source, Consumer<Apple> consumer){
        List<Apple> resault = new ArrayList<>();
        for(Apple a:source){
               consumer.accept(a);
        }
    }
}

总结:接口里面唯一的方法是accept。返回值是void。lambda表达式传的指是各种操作,也也就是accept的实现。

Function:

public class FunctionUse {
    private static String testFunction(Apple apple, Function<Apple, String> fun) {
        return fun.apply(apple);
    }

    /**
     * 这个就是可以有两个参数的意思
     * @param color
     * @param weight
     * @param fun
     * @return
     */
    private static Apple testBiFunction(String color, long weight, BiFunction<String,Long,Apple> fun) {
       return fun.apply(color,weight);
    }

    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 150), new Apple("yellow", 120),
                new Apple("green", 170), new Apple("red", 170));
        System.out.println(testFunction(list.get(0), (a) -> a.getColor()));

        IntFunction<Double> f = i -> i * 100d;
        System.out.println(f.apply(5));

        System.out.println(testBiFunction("green", 170,(s,w) -> new Apple(s,w)));
    }

}

总结:接口里面唯一的方法是apply,返回值是定义在泛型里面的。

Supplier:

public class SupplierUse {
    public static void main(String[] args) {
        Supplier<String> s = String::new;
        System.out.println(s.getClass());
        System.out.println(createApple(()->new Apple("Greem",100)));

    }

   private static Apple createApple(Supplier<Apple> supplier){
        return supplier.get();
   }
}

总结:里面只有一个get方法,返回值是在泛型里面定义的。

总结:四个类型其实都是传入的lambda就是实现这个接口的唯一的方法而new出来的实例,再用这个实例调用这个方法。

关于final:

这个是错误的。

        int i=0;
//        Runnable run = new Runnable(){
//            @Override
//            public void run() {
//                System.out.print(i);
//            }
//        };

        Runnable run1 = ()->System.out.print(i);
i++//i++的话输出那一行会报错的

------------------------------------------------------------04------------------------20200102--------------------------------------------------------------------

代码:

什么情况下可以用函数推导:

  • 类里面有静态方法:
Function<String,Integer> f = Integer::parseInt;
        System.out.println(f.apply("123888"));

带参数和返回值的::表达式。

------------------------------------------------------------05------------------------2020103----------------------------------------------------------------------

  • 通过实例方法就是类方法
 BiFunction<String,Integer,Character> f2 = String::charAt;
        Character c = f2.apply("hello",2);
        System.out.println(c);
  • 对象的实例方法
  String s = new String("hello");
        Function<Integer,Character> f3 = s::charAt;
        Character c2 = f3.apply(4);
        System.out.println(c2);

java8教程:http://blog.didispace.com/books/java8-tutorial/ch7.html

Function只有两个入参怎么办呢?我们要定义三个呢?

第一步:我们定义一个接口ThreeFunction

第二步:

方法推到到此为止。

-----

写法对比:

我们看下源码:

 

---

推荐一个网站:

--------------------------------------------------------------06---------------------------------------------------------------------------------------

代码位置:java07

filter传的是这个:

Predicate返回值是boolean。

// 第二个实验 注意这个写法 现在我看明白了
    private static List<String> getDishNamesByStream(List<Dish> menu) {
        return menu.parallelStream().filter(d -> {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return d.getCalories() < 400;
                }
        ).sorted(comparing(Dish::getCalories)).map(Dish::getName).collect(toList());
    }

Dish::getName:返回的是function。

注意带参数和返回值的::表达式是怎么写的。

什么是streams?

操作collections,可以并行去处理不需要关注并行处理的细节的。

这个根据cpu的核数划分为列表,再给不同的线程。

实验:

第一步:jconsole

第二步:代码还是上面的代码。

第三步:看实验结果

--------------------------------------------------------------07----------------------------------------------------------------------------------------

知识点:

Streams知识点总结:

可以处理collections和i/o的一些东西。

这些东西是如何决定角色的?

第一个:Dish

第二个:menu

第三个:filter  map collect......动作。

图解:

 

举例:

  下面的代码是报错的,流只能操作一次,不能操作多次的。


Stream<Dish> stream = menu.stream();
stream.forEach(System.out::println);
stream.forEach(System.out::println);

知识点:

结合上面的图:电脑本身去播放,不需要插入DVD的碟片。

知识点:动作

foreach也是termianl的。

知识点:

 List<String> result = menu.stream().filter(d -> {

            System.out.println("filtering->" + d.getName());
            return d.getCalories() > 300;
        })
                .map(d -> {
                    System.out.println("map->" + d.getName());
                    return d.getName();
                })
                .limit(3).collect(toList());

看下工作的过程:

fulter一次map一次不是全部都做完的。

知识点:

stream的anyMatch和allMatch。。。。。。。

知识点:

如何创建stream?

知识点:去重

--------------------------------------------------------------08--------------------------------------------------------------------------------------

代码:0910

如何创建stream?

知识点:collection是提供了stream的方法的。

代码1:

这个是完全的保持一致放在stream里面。

代码2:

代码3:

知识点:

代码4:

--------------------------------------------------------------09---------------------------------------------------------------------------------------

代码:在迭代器去创建的这个打印为18

代码:generate去创建

   private static Stream<Double> createStreamFromGenerate() {
        return Stream.generate(Math::random).limit(10);
    }

  

代码:流对象

  private static Stream<Obj> createObjStreamFromGenerate() {
        return Stream.generate(new ObjSupplier()).limit(10);
    }

总结:

------------------------------------------------------------------------------10------------------------------------------------------------------------

StreamFilter就是过滤一些元素的:

public static void main(String[] args) {
       List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 6, 7, 7, 1);
       // 基本的过滤
       List<Integer> result = list.stream().filter(i -> i % 2 == 0).collect(toList());
       System.out.println(result);
       System.out.println("=====================================================");
       // 去重
       result = list.stream().distinct().collect(toList());
       System.out.println(result);
       // 跳过
       result = list.stream().skip(50).collect(toList());
       System.out.println(result);
       // 限制
       result = list.stream().limit(50).collect(toList());
       System.out.println(result);
       // 遍历 返回值事null
       list.forEach(System.out::println);
       list.forEach(i -> System.out.println(i));
       list.forEach((Integer i) -> System.out.println(i));
       for (int i : list) {
            System.out.println(i);
        }
    }

map是对每个元素去操作的:

   public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 6, 7, 7, 1);
       
        // 基本的操作 在流里面取出每个i每个i是一个Integer的
        List<Integer> result = list.stream().map(i -> i * 2).collect(toList());

        System.out.println(result);

        // 基本操作
        listDish().stream().map(d -> d.getName()).forEach(System.out::print);

        List<String> dishes = listDish().stream().map(d -> d.getName()).collect(toList());
        System.out.println(dishes);

        //flatmap flat (扁平化)

        String[] words = {"Hello", "World"};

        //{h,e,l,l,o},{W,o,r,l,d}
        Stream<String[]> stream = Arrays.stream(words).map(w -> w.split(""));//Stream<String[]>

        //H,e,l,l,o,W,o,r,l,d
        // 将多个stream合并到一起
        Stream<String> stringStream = stream.flatMap(Arrays::stream);
        // 可以这么改下 进去的是两个字符串数组 取出来的是流里面的数组
        Stream<String> stringStream = stream.flatMap(str->Arrays.stream(str));
        stringStream.distinct().forEach(System.out::print);

    }

------------------------------------------------------------------------------11------------------------------------------------------------------------

这几个说下。

---

StreamMatch:

public static void main(String[] args) {

        Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});

        boolean matched = stream.allMatch(i -> i > 10);
        System.out.println(matched);


        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        matched = stream.anyMatch(i -> i > 6);

        System.out.println(matched);

        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        matched = stream.noneMatch(i -> i < 0);
        System.out.println(matched);

    }

StreamFind:

public static void main(String[] args) {
        Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        // 找任意一个
        Optional<Integer> optional1 = stream.filter(i -> i % 2 == 0).findAny();
        System.out.println(optional1.get());
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        Optional<Integer> optional3 = stream.filter(i -> i > 10).findAny();
        // orElse
        System.out.println(optional3.orElse(-1));
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        Optional<Integer> optional2 = stream.filter(i -> i % 2 == 0).findFirst();
        // 存在打印
        optional2.ifPresent(System.out::println);
        // 对optional继续过滤
        System.out.println(optional2.filter(i -> i == 2).get());
        //自定义方法实现orElse
        int result = find(new Integer[]{1, 2, 3, 4, 5, 6, 7}, -1, i -> i < 10);
        System.out.println(result);
    }

Optional的语法:

StreamReduce:相当于聚合,根据给定的Function操作,BiFunction就是两个入参的Function。

  public static void main(String[] args) {

        Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});

        Integer result = stream.reduce(0, Integer::sum);
        System.out.println(result);

        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
      
        // 不给初始值就是Optional的
        stream.reduce((i, j) -> i + j).ifPresent(System.out::println);

         // ======================================================
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});

        stream.reduce(Integer::max).ifPresent(System.out::println);

        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        stream.reduce(Integer::min).ifPresent(System.out::println);

        // ========================================================
        // 返回的是最大值 7
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        stream.reduce((i, j) -> i > j ? j : i).ifPresent(System.out::println);


        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});

        int result2 = stream.filter(i -> i % 2 == 0).reduce(1, (i, j) -> i * j);

        Optional.of(result2).ifPresent(System.out::println);

    }

------------------------------------------------------------------------------12------------------------------------------------------------------------

NumberStreams:

这个是节省内存的。

boxed是封箱的意思。

 public static void main(String[] args) {
        /*Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});

        // 为什么是intValue是因为操作的是Integer类型的
        IntStream intStream = stream.mapToInt(i -> i.intValue());

        int result = intStream.filter(i -> i > 3).sum();

        System.out.println(result);*/


        int a = 9;

        //1..1000
        //result int[a,b,c];

        IntStream.rangeClosed(1, 100)
                .filter(b -> Math.sqrt(a * a + b * b) % 1 == 0)
                .boxed()
                .map(b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)})
                .forEach(r -> System.out.println("a=" + r[0] + ",b=" + r[1] + ",c=" + r[2]));

        System.out.println("=======================");


        IntStream.rangeClosed(1, 100)
                .filter(b -> Math.sqrt(a * a + b * b) % 1 == 0)
                 // 这之前的IntStream 给的是b返回的是r 就是变回了普通的stream了
                .mapToObj(b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)})
                .forEach(r -> System.out.println("a=" + r[0] + ",b=" + r[1] + ",c=" + r[2]));
    }

------------------------------------------------------------------------------13-------------------------------------------------------------------------

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值