by shihang.mai
1. lambda表达式特点
-
函数式编程
-
参数类型自动推断
-
代码量少,简洁
可以用在任何有函数式接口的地方
2. jdk提供的函数式接口
接口 | 方法 | 作用 |
---|---|---|
Supplier<T> | T get(); | 没输入,1个输出 |
Consumer<T> | void accept(T t) | 1个输入,没输出 |
BiConsumer<T, U> | void accept(T t, U u) | 2个输入,没输出 |
Function<T, R> | R apply(T t) | 1个输入,1个输出,输入输出不同类型 |
UnaryOperator<T> | T apply(T t) | 1个输入,1个输出,输入输出相同类型 |
BiFunction<T, U, R> | R apply(T t, U u) | 2个输入,1个输出,3个都不同类型 |
BinaryOperator<T> | T apply(T t, T t) | 2个输入,1个输出,3个都相同类型 |
3. Lambda使用
只有一个抽象方法的接口就是函数式接口,一般地在函数式接口上加上注解@FunctionInterface
@FunctionInterface
public interface IUser {
void add()
}
public class Test{
public static void main(String[] args) {
/**
* ()指方法中有没参数,当超过一句代码时,要用中括号,如
* IUser user = () ->{System.out.println("....");};
*/
IUser user = () ->System.out.println("....");
}
}
3.1 方法引用
类型 | 语法 |
---|---|
静态方法引用 | 类名::staticMethod |
实例方法引用 | ins::insMethod |
对象方法引用 | 类名::insMethod |
构造方法引用 | 类名::new |
3.2 Stream
3.2.1 source
- 数组
public static void main(String[] args) {
String [] arr= {"m","s","h"};
Stream<String> arrStream = Stream.of(arr);
}
- 集合
public static void main(String[] args) {
List<String> list = Arrays.asList("m", "s", "h");
Stream<String> listStream = list.stream();
}
- Stream.generate()
public static void main(String[] args) {
Stream<Integer> generate = Stream.generate(() -> 123);
}
- Stream.iterate
public static void main(String[] args) {
Stream<Integer> iterate = Stream.iterate(1, (x) -> x + 1);
}
- other
public static void main(String[] args) {
String str = "msh";
IntStream chars = str.chars();
}
public static void main(String[] args) {
Stream.of(1,2,3,4,5,6);
}
3.2.3 middle
- filter
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5,6);
Stream<Integer> stream = integers.stream();
stream.filter((x) -> x % 2 == 0);
}
- mapToInt
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5,6);
Stream<Integer> stream = integers.stream();
int sum = stream.filter((x) -> x % 2 == 0).mapToInt((x) -> x).sum();
System.out.println(sum);
}
limit
skip
distinct
sorted
3.2.4 end
- sum
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5,6);
Stream<Integer> stream = integers.stream();
int sum = stream.filter((x) -> x % 2 == 0).mapToInt((x) -> x).sum();
System.out.println(sum);
}
- max
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5,6);
Stream<Integer> stream = integers.stream();
Optional<Integer> max = stream.filter((x) -> x % 2 == 0).max((a, b) -> a - b);
System.out.println(max.get());
}
- min
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5,6);
Stream<Integer> stream = integers.stream();
Optional<Integer> min = stream.filter((x) -> x % 2 == 0).min((a, b) -> a - b);
System.out.println(min.get());
}
- findAny
- findFirst
- collect
- allMatch
- anyMatch
- noneMatch
- count
- forEach
- reduce
网友评论