Lambda表达式
最近学习了一下java的函数式编程(Lambda),做个笔记方便以后可以使用:
public class Java8Tester {
/*
Lambda 四大核心内置函数式接口
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);
*/
public static void main(String args[]){
// 调用函数式的方法
getA("Hello Lambda");
// 循环的使用
listFor();
ProductTag t = new ProductTag();
t.setTagId(1L);
t.setTagName("name");
System.out.println(getTag(t));
}
public static ProductTag getTag(ProductTag tag){
Supplier<ProductTag> action = () ->{
ProductTag entity = new ProductTag();
entity = tag;
return entity;
};
return exec(action);
}
public static <T> T exec(Supplier<T> _actien){
T result = null;
try{
result = _actien.get();
}catch (Exception ex){
System.out.println("出现异常了,快回滚");
}
return result;
}
// 函数式调用
public static String getA(String a){
MyLambdaInterface face = () -> {
int i = 1/0;
System.out.println("- " + a);
return "- " + a;
};
return getB(face);
}
public static String getB(MyLambdaInterface myLambdaInterface){
String result = "";
try{
result = myLambdaInterface.doSomething();
}catch (Exception ex){
System.out.println("出现异常了,快回滚");
}
return result;
}
// 循环的使用
public static void listFor(){
// list的遍历
List<String> list = new ArrayList<>();
list.add("list1");
list.add(null);
list.add("list2");
list.add("list3");
list.forEach(obj -> System.out.println("list测试:" + obj));
list.forEach(obj -> {
System.out.println("list测试方法体:" + obj);
});
// map的遍历
Map<String, Object> map = new HashMap<>();
map.put("map1", "mapValue1");
map.put("map2", "mapValue2");
map.put("map3", "mapValue3");
map.forEach((k, v) -> {
System.out.println("map测试方法体:k=" + k + ", v=" + v);
});
// 循环赋值 filter过滤空
List<String> list2 = new ArrayList<>();
list2 = list.stream().filter(Objects::nonNull).map(str -> {
return "list.stream().map :" + str;
}).collect(Collectors.toList());
list2.forEach(obj -> System.out.println("list2 = " + obj));
// 循环赋值 filter过滤指定值
List<String> list3 = new ArrayList<>();
list3 = list.stream().filter(s -> s != "list2").map(str -> {
return "list.stream().filter.map :" + str;
}).collect(Collectors.toList());
list3.forEach(obj -> System.out.println("list3 = " + obj));
}
@FunctionalInterface
interface MyLambdaInterface{
String doSomething();
}
}