Lambda表达式是一个匿名函数,即没有函数名的函数。从动态引用到动态定义,可以简化写法。
对比两种写法:
Lambda表达式的语法如下:
(parameters) -> expression
或
(parameters) ->{ statements; }
还有如下特性:
示例:
() -> 5
x -> x*2
(x,y) -> x-y
(int x,int y) -> x+y
(String x) -> System.out.print(x)
Java8给我们提供了一些接口,可供使用:
还有很多,都在java.util.function包里面。
示例:
//java7写法
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(new Date());
}
}).start();
//java8 写法
new Thread(()-> System.out.println(new Date())).start();
Stream(流)是一个来自数据源的元素队列并支持聚合操作
创建Stream的几种方式:
String[] array={"a","b","c","d"};
Stream<String> stream1 = Stream.of(array);
Stream<String> stream2 = Arrays.stream(array);
List<Integer> list=new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.stream();
Stream<String> stream3 = Stream.generate(() -> "love").limit(10);
Stream<BigInteger> bigIntStream = Stream.iterate(BigInteger.ZERO, n -> n.add(BigInteger.ONE)).limit(10);
Stream stream = Stream.concat(stream1, stream2);
Stream<String> wordStream = Pattern.compile("\\W").splitAsStream(sentence);
Stream操作:
中间操作:
终止操作:
代码示例:
public static void main(String[] args) {
List<Integer> list=new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.stream().filter(x->x>2).forEach(System.out::println);
list.stream().mapToDouble(x->Double.valueOf(x)).forEach((b)-> System.out.println(b));
list.stream().flatMap(x->Arrays.stream(new Integer[]{x})).forEach(System.out::println);
boolean flag = list.stream().anyMatch(x -> x % 3 == 0);
long count = list.stream().count();
System.out.println("元素个数:"+count);
long sum = list.stream().collect(Collectors.summarizingInt(x -> x)).getSum();
System.out.println("总元素的和是:"+sum);
Integer integer = list.stream().reduce((a, b) -> a + b).get();
System.out.println("规约求和:"+integer);
}
原文:https://www.cnblogs.com/javammc/p/14916076.html