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]
原文地址:https://www.cnblogs.com/yejiang/p/10973256.html