• 学习笔记-java函数式编程


    lambda

    案例

    案例1

    new Threaad(new Runable(){
        public void run(){
            System.out.println("xxx"):
        }
    }).start();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    new Thread(()->
        {
            System.out.println("xxx")}
    ).star();
    
    • 1
    • 2
    • 3
    • 4
    • 5

    案例2

    public static int calculateNum(IntBinaryOperator operator){
        int a = 10;
        int b = 200;
        return operator.applyAsInt(a,b);
    }
    public void main(String[] args){
        calculateNum( (a,b)-> a*b );
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    案例3

    public static void printNum(Inpredicate predicate){
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        for(int i: arr){
            if(predicate.test(i)){
                System.out.println(i);
            }
        }
    }
    
    public void main(String[] args){
        printNum(x->{
            return x%2==0;
        })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    案例4

    public static <R> R typeConver(Function<String,R> function){
        String str = "12345";
        R result = function.apply(str);
        return result;
    }
    
    public void main(String[] args){
        Integer result = typeConver(x->Integer.valueOf(x));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    案例5

    public static void foreachArr(IntConsumer consumer){
        int[] arr = {1,2,3,4,5,6,7,8};
        for(int i:arr){
            consumer.accept(i);
        }
    } 
    
    public void main(String[] args){
        foreachArr(x->System.out.println(x));
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    Stream

    案例

    • 数据准备
    public class Author{
        private Long id;
        private String name;
        private Integer age;
        private String intro;
        private List<Book> books;
    }
    
    public class Book{
        private Long id;
        private String name;
        private String category;
        private Integer score;
        private String intro;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    private static List<Autor> getAutors(){
        Author a1 = new Author(1l,"xx",22,"xxx",null);
        Author a2 = new Author(2l,"xx",33,"xxx",null);
        Author a3 = new Author(3l,"xx",44,"xxx",null);
        Author a4 = new Author(4l,"xx",55,"xxx",null);
        
        List<Book> b1 = new ArrayList<>();
        List<Book> b2 = new ArrayList<>();
        List<Book> b3 = new ArrayList<>();
    
        b1.add(new Book(1l,"xxxx","xxx",88,"xxxxxxxxx"));
        b1.add(new Book(2l,"xxxx","xxx",89,"xxxxxxxxx"));
        b1.add(new Book(3l,"xxxx","xxx",90,"xxxxxxxxx"));
        
        b2.add(new Book(4l,"xxxx","xxx",91,"xxxxxxxxx"));
        b2.add(new Book(5l,"xxxx","xxx",92,"xxxxxxxxx"));
        b2.add(new Book(6l,"xxxx","xxx",95,"xxxxxxxxx"));
        
        b3.add(new Book(7l,"xxxx","xxx",98,"xxxxxxxxx"));
        b3.add(new Book(8l,"xxxx","xxx",99,"xxxxxxxxx"));
        b3.add(new Book(9l,"xxxx","xxx",100,"xxxxxxxxx"));
        
        a1.setBooks(b1);
        a2.setBooks(b2);
        a3.setBooks(b3);
        a4.setBooks(b3);
        
        List<Author> authorList = new ArrayList<>(Arrays.asList(a1,a2,a3,a4));
        
        return authorList;
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    创建流

    // 年龄小于18 去重 打印
    List<Author> authors = getAuthors();
    authors.stream()
        .distinct()
        .filter(x->x.getAge()<18)
        .forEach(x->System.out.println(x.getName()));
    
    // 数组创建
    Integer[] arr = {1,2,3,4,5};
    Arrays.stream(arr).distinct().forEach(x->System.out.println(x));
    Stream.of(arr);
    // Set
    HashMap<String, String> map=new HashMap<>();
    Set<Map.Entry<String, String>> set=map.entrySet();
    set.stream();
    // Map
    Map map = new HashMap();
    map.entrySet().stream();
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    中间操作

    // filter
    // 打印姓名长度大于1
    authors.stream()
        .filter(x->x.getName().length()>1)
        .forEach(x->System.out.println(x.getName()));
    
    // map
    // 打印所有姓名
    authors.stream().forEach(x->System.out.println(x.getName()));
    authors.stream().map(x->x.getName()).forEach(x->System.out.println(x));
    
    // distinct
    // 打印所有姓名 去重
    authors.stream().distinct().map(x->x.getName()).forEach(x->System.out.println(x));
    
    // sorted
    // 姓名去重 年龄排序
    // implements Comparable
    // public int compareTo(Author o){} 
    authors.stream().distinct().sorted((a,b)->a.getAge()-b.getAge()).forEach(x->System.out.println(x.getAge() ));
    
    // limit
    // 排序后限制2个
    authors.stream().distinct().sorted((a,b)->a.getAge()-b.getAge())
        .limit(2).forEach(x->System.out.println(x.getName() ));
    
    
    // skip
    // 排序 跳过1个
    authors.stream().distinct().sorted((a,b)->b.getAge()-a.getAge()).skip(1).forEach(x->System.out.println(x.getName() ));
    
    // flatMap
    authors.stream().flatMap(x->x.getBooks().stream()).distinct().forEach(x->System.out.println(x.getName() );
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    终结操作

    // forEach
    authors.stream().forEach(x->System.out.println(x.getName()));
    
    // count
    authors.stream().flatMap(x->x.getBooks().stream())
        .distinct().count();
    
    // min max
    authors.stream().distinct().flatMap(x->x.getBooks().stream()).map(x->x.getSocre()).max((a,b)->a-b).get();
    authors.stream().distinct().flatMap(x->x.getBooks().stream()).map(x->x.getSocre()).min((a,b)->a-b).get();
    
    // collect
    // list
    authors.stream().map(x->x.getName()).collect(Collectors.toList());
    // set
    authors.stream().map(x->x.getName()).collect(Collectors.toSet());
    // map
    authors.stream()
        .collect(Collectors.toMap(x->x.getName(),x->x.getBooks())) ;
    
    // anyMatch
    authors.stream().anyMatch(x->x.getAge()>10);
    
    // allMatch
    authors.stream().allMatch(x->x.getAge()>10);
    
    // noneMatch
    authors.stream().noneMatch(x->x.getAge()>10);
    
    
    // findAny
    // 随机获取
    authors.stream().filter(x->x.getAge()>18).findAny();
    
    // findFirst
    authors.stream().sorted((a,b)->a.getAge()-b.getAge()).findFirst();
    
    // reduce
    // 求和
    authors.stream().distinct().map(x->x.getAge()).reduce(0,(a,b)->a+b);
    // 最大值
    authors.stream().distinct().map(x->x.getAge()).reduce(0,(a,b)->a>b?a:b);
    authors.stream().distinct().map(x->x.getAge()).reduce((a,b)->a>b?a:b);
    // 最小值
    authors.stream().distinct().map(x->x.getAge()).reduce(100,(a,b)->a>b?b:a);
    authors.stream().distinct().map(x->x.getAge()).reduce((a,b)->a>b?b:a);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    optional

    创建

    // 不确定author是否为空
    Optional<Author> op = Optional.ofNullable(author);
    // 确定object不为空
    Optional.of(object);
    // 返回空
    Optional.empty()''
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    操作

    // 如果存在
    op.ifPresent(x->System.out.println(x.getName()));
    
    // 获取 
    // 如果没有 创建默认值
    op.orElseGet(()->new Author());
    // 如果没有 抛出异常
    op.orElseThrow(()->new Exception("xxx"));
    
    // 过滤
    // 返回一个OPtional对象
    op.fliter(x->x.getAge()>18);
    
    // 判断
    op.isPresent();
    
    // 数据转换
    op.map(x->x.getBooks())
        .ifPresent(x->System.out.println(x.size());
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    函数式接口

    • 注解

      • @FunctionalInterface
    • 接口

      • Consumer
        • void accept(T t)
        • BiConsumer
          • void accept(T t,U u)
      • Function
        • R apply(T t)
        • BiFunction
          • R accept(T t,U u)
      • Predicate
        • boolean test(T t)
        • BiPredicate
          • boolean accept(T t,U u)
      • Supplier
        • T get()
        • BooleanSupplier
          • boolean getAsBoolean()
    • 默认方法

    // Predicate and()
    authors.stream()
        .filter((x->x.getAge()>17).and(x->x.getName().length()>1))
        .forEach(x->System.out.println(x.getAge()));
    // Predicate negate()
    // 取反
    // 取不大于17
    authors.stream()
        .filter((x->x.getAge()>17).negate())
        .forEach(x->System.out.println(x.getAge()));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    方法引用

    • 类名或对象名::方法名
      • 不会的话可以使用idea自动生成。。。

    数据类型转换

    // mapToInt
    authors.stream()
        .mapToInt(x->x.getAge())
        .fotEach(System.out::println);
    
    • 1
    • 2
    • 3
    • 4

    并行流

    // parallel() 开启并行流
    // 或直接list.parallelStream()
    // peek() 调试
    Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);
    stream.parallel()
        .peek(x->System.out.println(x+Thread.currentThread().getName()))
        .filter(x->x>5)
        .reduce((result,ele)->result+ele)
        .get();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  • 相关阅读:
    普通二本+转专业学计算机是什么感受
    MySQLJDBC入门与SQL注入
    C#连接MySql数据库
    LeetCode经典面试150题-day5(多数元素)
    如何开始做股票量化交易?
    功能测试如何进阶自动化测试?5个步骤带你成功进阶...
    nginx反向代理与负载均衡
    单链表的实现(Single Linked List)---直接拿下!
    python数据结构补充——树
    ODrive移植keil(八)—— 闭环控制
  • 原文地址:https://blog.csdn.net/weixin0605/article/details/128008463