• java8 lambda表达式


    java8 lambda表达式

    一些注意

    • 首先需要将list或是数组Stream一下

    stream of elements ---> filter ---> sorted ---> map ---> collect( Collectors.toList )

    • 例子:
      [4,3,2,1,6,7,8]

    map

            System.out.println(a.stream().map(x->x+1).collect(Collectors.toList()));
    		System.out.println(a.stream().map((x)->6).collect(Collectors.toList()));
    
    输出:
    
            [5, 4, 3, 2, 7, 8, 9]
            [6, 6, 6, 6, 6, 6, 6]
    

    fliter

            System.out.println(a.stream().filter(x->x>4).sorted().collect(Collectors.toList()));
    		System.out.println(a.stream().filter((x)->{
    			if(x==2){
    				return true;
    			}else{
    				return false;
    			}
    		}).collect(Collectors.toList()));
    
    输出:
    
            [6, 7, 8]
            [2]
    

    reduce

            //累加
    		int r1 = a.stream().reduce((x,y)->{
    			return x+y;
    		}).get();
    		System.out.println(r1);
    		//累乘
    		int r2 = a.stream().reduce((x,y)->{
    			return x*y;
    		}).get();
    		System.out.println(r2);
    
    输出:
    
            31
            8064
    

    sorted

            System.out.println(a.stream().sorted().collect(Collectors.toList()));
    		//两个参数
    		System.out.println(a.stream().sorted((x,y)->{
    			if(x > y){
    				return -1;
    			}else{
    				return 1;
    			}
    		}).collect(Collectors.toList()));
    		/*
    		 * compareTo
    		 * 如果相等则返回0
    		 * 小于返回-1
    		 * 大于返回1
    		 * */
    		System.out.println(a.stream().sorted((x,y)->x.compareTo(y)).collect(Collectors.toList()));
    
    输出
    
            [1, 2, 3, 4, 6, 7, 8]
            [8, 7, 6, 4, 3, 2, 1]
            [1, 2, 3, 4, 6, 7, 8]
    
  • 相关阅读:
    jquery queryBuilder过滤插件的使用
    前端跨域问题
    [BZOJ 3326] 数数
    [BZOJ 2427] 软件安装
    [BZOJ 3675] 序列分割
    [Atcoder Grand Contest 004] Tutorial
    [P2831] 愤怒的小鸟
    [Atcoder Regular Contest 065] Tutorial
    [P3806] Divide and Conquer on Tree
    [POJ 1741] Tree
  • 原文地址:https://www.cnblogs.com/yejiang/p/10973256.html
Copyright © 2020-2023  润新知