1 函数式创建对象
new接口或抽象类时在花括号里面补全缺失的函数体可以创建匿名子类对象(非子类匿名对象)
new普通类时在花括号里面直接重写方法可以创建匿名子类对象(非子类匿名对象)
2 lumbda表达式创建对象
- 在函数式创建对象的基础上当接口或抽象类中仅有一个方法缺少函数体时可以使用lumbda表达式创建对象:(/形参/) -> {/函数体/}
- 当仅有一个形参时可以简化lumbda:/形参/ -> {/函数体/}
- 当仅函数体仅有一条语句可以简化lumbda:(/形参/) -> /函数体/
3 常用的函数式接口
- public interface Consumer
//1个入参,0个返回值 - public interface Predicate
//1个入参,1个布尔返回值 - public interface Function<T, R> //1个入参,1个返回值
- public interface Supplier
//0个入参,1个返回值
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class M1 {
public static void main(String[] args) throws ParseException {
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(new String[] {"aaa","bbb","ccc"}));
Consumer<String> consumer = new Consumer<String>() {
@Override
public void accept(String s) {
arrayList.add(s);
}
};
consumer.accept("ddd");
System.out.println(Arrays.toString(arrayList.toArray()));
Predicate<String> predicate = new Predicate<String>() {
@Override
public boolean test(String s) {
return arrayList.contains(s);
}
};
boolean b = predicate.test("aaa");
System.out.println(b);
Function<String,Integer> function = new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return arrayList.indexOf(s);
}
};
Integer i = function.apply("aaa");
System.out.println(i);
Supplier<String> supplier = new Supplier<String>() {
@Override
public String get() {
return arrayList.get(0);
}
};
String s = supplier.get();
System.out.println(s);
}
}
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class M2 {
public static void main(String[] args) throws ParseException {
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(new String[] {"aaa","bbb","ccc"}));
Consumer<String> consumer = s -> arrayList.add(s);
consumer.accept("ddd");
System.out.println(Arrays.toString(arrayList.toArray()));
Predicate<String> predicate = s -> arrayList.contains(s);
boolean b = predicate.test("aaa");
System.out.println(b);
Function<String,Integer> function = s -> arrayList.indexOf(s);
Integer i = function.apply("aaa");
System.out.println(i);
Supplier<String> supplier = () -> arrayList.get(0);
String s = supplier.get();
System.out.println(s);
}
}
[aaa, bbb, ccc, ddd]
true
0
aaa
标签:function,java,函数,arrayList,编程,util,import,public
From: https://www.cnblogs.com/gaoguanghui/p/18617789