java复习十:jdk8新特性lambda表达式

package com.example.demo;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * java8  关于lambda表达式使用
 */
public class LambdaTest {


    public static void main(String[] args) {
        List list = Arrays.asList("12","23","354","565");
        List listInt = Arrays.asList(1,2,3);
//        newThread();
//        iteratorList(list);
//        filter(list,(str)->(str.toString().length()==2));
//        updateList(listInt);
        statisList(listInt);
    }



    //1 创建线程,用 lambda 表达式实现 Runnable
    public static void newThread(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("1.thread----");
            }
        }).start();
        new Thread( () -> System.out.println("1.thread----") ).start();
    }
    //2.遍历list
    public static void  iteratorList(List list){
        list.forEach((i)-> System.out.println(i));
    }

    //3.过滤,返回符合条件的list
    public static void filter(List list, Predicate predicate){
        list.stream().filter((l)->(predicate.test(l))).forEach((l)-> System.out.println(l));
    }
    //4.修改list元素,不改变原来list,创建新的list
    public static void updateList(List list){
        list.stream().map((l)->l*l).collect(Collectors.toList()).forEach((l)-> System.out.println(l));
        Integer integer = list.stream().map((l) -> l * l).reduce((sum, l) -> sum + l).get();
        System.out.println(integer);
        System.out.println("---");
        list.forEach((li)-> System.out.println(li));
    }

    //5.計算list統計值
    public static void statisList(List list){
        IntSummaryStatistics intSummaryStatistics = list.stream().mapToInt((a -> a)).summaryStatistics();
        System.out.println(intSummaryStatistics.getAverage());
        System.out.println(intSummaryStatistics.getMax());
        System.out.println(intSummaryStatistics.getMin());
        System.out.println(intSummaryStatistics.getSum());
    }
    //6.lambda表达式的局限,可以访问域外变量,但是不能修改。
    //7.lambda表达式会被编译成private静态方法。

}

 

你可能感兴趣的:(java)