我们实现接口有很多种形式其中一种就是匿名实现类的方式:
我们先定义一个接口 (@FunctionalInterface 函数式接口:接口中只定义一个方法的接口称之为函数是接口)
@FunctionalInterface
public interface InterfaceLamdaFunction1 {
int get(Integer t);
}
实现接口
@Test
public void e() {
/*匿名内部类实现*/
InterfaceLamdaFunction1 function1 =new InterfaceLamdaFunction1() {
@Override
public void get(Integer t) {
return t;
}
};
}
lambda实现方式
lambda表达式可以看作是简化了匿名内部类实现
@Test
public void g() {
InterfaceLamdaFunction1 function1 = (Integer x) -> {return x;};
}
当前表达式 (Integer x) -> {return x;}; 是对InterfaceLamdaFunction1 接口的实现 其中 (Integer x) 是接口中get方法的参数列表 右侧是 {return x;}; 对get方法的 @Override。
lambda 的语法
(Integer x) -> {return x;}; 其中 -> 左侧为 方法参数列表 右侧为方法体。
左侧的类型可以省略 (x) -> {return x;};
右侧方法体如果只有一行代码 {} 和 return 也可以省略 (x) -> x;
java.util.function 包中定义了很多函数式接口
其中有四个基本的函数式接口
1.消费型接口: Consumer<T> : void accept(T t)
2.供给型接口: Supplier<T> : T get()
3.函数型接口: Function<T,R> : R apply(T t)
4.断定型接口: Predicate<T> : boolean test(T t)
简单使用列子
1 消费型
public void listConsumer(List<String> list,Consumer<String> consumer) {
List<String> data = new LinkedList<>();
for (String s : list) {
consumer.accept(s);
}
}
@Test
public void b() {
List<String> list = Arrays.asList("一", "一二", "一二三");
listConsumer(list,x-> System.out.println(x));
}
2.供给型
@Test
public void c() {
List<Integer> list = getNumList(10, () -> (int) (Math.random() * 100));
list.forEach(System.out::println);
}
public List<Integer> getNumList(int num, Supplier<Integer> sup) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
list.add(sup.get());
}
return list;
}
3函数型
public List<String> listFunction(List<String> list, Function<String, String> function) {
List<String> data = new LinkedList<>();
for (String s : list) {
data.add(function.apply(s));
}
return data;
}
@Test
public void d() {
List<String> list = Arrays.asList("一", "一二", "一二三");
list = listFunction(list, (x) -> x + "function");
list.forEach(x -> System.out.println(x));
}
4 断定型
public List<String> getList(List<String> list, Predicate<String> pre) {
List<String> data = new LinkedList<>();
for (String s : list) {
if (pre.test(s)) {
data.add(s);
}
}
return data;
}
@Test
public void a() {
List<String> list = Arrays.asList("一", "一二", "一二三");
List<String> data = getList(list, s -> s.length()==1);
System.out.println(data);
}