J2SE 8的Lambda --- functions
functions
//1. Runnable 输入参数:无 返回类型void
new Thread(() -> System.out.println("In Java8!") ).start();
System.out.println();
//2.Predicate<T> 输入参数:t 返回类型boolean
List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
// case1, 用流fliter,再 foreach遍历,传入Predicate 判断boolean
System.out.println("Languages which starts with J :");
filter(languages, (str)->str.startsWith("J"));
System.out.println();
Predicate<String> jSatrtConditions =(str)->str.startsWith("J");
Predicate<String> aEndsConditions =(str)->str.endsWith("a");
//case2, 两个&&关系
filter(languages, jSatrtConditions.and(aEndsConditions));
System.out.println();
//case3, 两个||关系
filter(languages, jSatrtConditions.or(aEndsConditions));
System.out.println();
//case4, 调用Predicate的静态isEqual方法
Predicate<String> predicateEqual = Predicate.isEqual("Java");
System.out.println(predicateEqual.test("JAVA"));
Predicate<String> and = predicateEqual.and(jSatrtConditions);
filter(languages, and);
System.out.println();
//3.Function<T,R> 输入参数:T 返回类型R
List<Integer> numList = Arrays.asList(100, 200, 300, 400, 500);
filter2(numList, n->n+1);
System.out.println();
//4.BiFunction<T, U, R> 输入参数:T,U 返回类型R
BiFunction<String, String,String> biFunction = (x,y)->x+y;
System.out.println(biFunction.apply("111", "222"));
System.out.println(biFunction.andThen(n->n+"*").apply("111", "222"));
System.out.println();
//5.BinaryOperator<T,T,T> 输入参数:T,T 返回类型T
//Represents an operation upon two operands of the same type, producing a result of the same type as the operands
Integer filter3Result = filter3(numList, n->n+1, (x,y)->x+y);
System.out.println(filter3Result);
System.out.println();
//第一步,和identity做相加生产新的数组
//第二步,新的数组每两个相乘
List<Integer> numList2 = Arrays.asList(1, 2, 3, 4, 5);
Integer filter4Result = filter4(numList2, 1, (x,y)->{
return x+y;
}, (x,y)->{
return x*y;
});
System.out.println(filter4Result);
System.out.println();
//6.Optional
//值不存在的情况下产生可替代物
ArrayList<String> arrayList = new ArrayList<>();
//(1) 创建Optional
//1) Optional.of() 它要求传入的 obj 不能是 null 值的, 否则还没开始进入角色就倒在了 NullPointerException 异常上了
Optional<String> stringOptional = Optional.of("stringOptional");
System.out.println(stringOptional.orElse(null));
System.out.println();
//2) Optional.ofNullable(obj): 它以一种智能的, 宽容的方式来构造一个 Optional 实例. 来者不拒, 传 null 进到就得到 Optional.empty(), 非 null 就调用 Optional.of(obj)
stringOptional = Optional.ofNullable(null);
System.out.println(stringOptional.orElse(null));
System.out.println();
//3) Optional.empty() 空的Optional
Optional<Object> emptyOptional = Optional.empty();
System.out.println(emptyOptional.orElse(null));
System.out.println();
//4) 自己创建
Optional<Double> inverseOptional = inverse(1.2);
System.out.println(inverseOptional.orElse(null));
System.out.println();
//(2) orElse() 值不存在的情况下的默认物
Optional<String> ofNullableOptional = Optional.ofNullable(null);
System.out.println(ofNullableOptional.orElse("default value"));
ofNullableOptional = Optional.empty();
System.out.println(ofNullableOptional.orElse("default value"));
System.out.println();
//(3) orElseGet() 值不存在的情况下, 提供Supplier
ofNullableOptional = Optional.ofNullable(null);
System.out.println(ofNullableOptional.orElseGet(()->new Date().toString()));
ofNullableOptional = Optional.empty();
System.out.println(ofNullableOptional.orElseGet(()->new Date().toString()));
System.out.println();
//(4) orElseThrow() 值不存在的情况下, 提供Supplier异常
try {
ofNullableOptional = Optional.ofNullable(null);
System.out.println(ofNullableOptional.orElseThrow(Exception::new));
} catch (Exception e) {
System.out.println("orElseThrow");
e.printStackTrace();
}
System.out.println();
try {
ofNullableOptional = Optional.empty();
System.out.println(ofNullableOptional.orElseThrow(Exception::new));
} catch (Exception e) {
System.out.println("orElseThrow");
e.printStackTrace();
}
System.out.println();
//(5) isPresent() 是否存在
boolean present = Optional.of("stringOptional").isPresent();
System.out.println(present);
present = Optional.empty().isPresent();
System.out.println(present);
System.out.println();
//(6) ifPresent() 如果存在,将元素传递给对应函数(比如将其加入集合或者做计算)
Optional.of("stringOptional").ifPresent(e->System.out.println(e));
Optional.of("stringOptional").ifPresent(System.out::println);
Optional.of("stringOptional").ifPresent(e->arrayList.add(e));
Optional.empty().ifPresent(e->System.out.println("xxx"));
System.out.println();
//(7) map() 将对应的值传递给mapper
Optional.of("map").map(e->arrayList.add(e));
System.out.println(arrayList);
Optional<Boolean> mapOptional = Optional.ofNullable("mapOptional").map(arrayList::add);
System.out.println(arrayList);
mapOptional = Optional.of("map").map(e->arrayList.add(e));
System.out.println(mapOptional.orElse(null));
//(8) get() 得到对应的值, 如果值不存在, 抛出exception
System.out.println(Optional.of("map").get());
//java.util.NoSuchElementException: No value present
// System.out.println(Optional.ofNullable(null).get());
Optional<Object> ofNullable = Optional.ofNullable(null);
if(ofNullable.isPresent()){
System.out.println(ofNullable.get());
}
//(9) flatMap() 组合两个返回Optional的方法 f(), g()
//方式一: f().float(T::g)
Optional<Double> flatMapOptional = inverse(1.2).flatMap(LambdaFunctionsTest::square);
System.out.println(flatMapOptional.orElse(null));
System.out.println();
//方式二: .float(T::f).float(T::g) 还可以在后面再.float(T::g)
flatMapOptional = Optional.of(1.2).flatMap(LambdaFunctionsTest::inverse).flatMap(LambdaFunctionsTest::square);
System.out.println(flatMapOptional.orElse(null));
System.out.println();
辅助方法
public static <T> void filter(List<T> names, Predicate<T> conditions){
names.stream().filter(conditions).forEach(name->System.out.println(name));
}
public static <T,R> void filter2(List<T> names, Function<T,R> function){
names.stream().map(function).forEach(name->System.out.println(name));
}
public static <T,R> R filter3(List<T> names, Function<T,R> mapFunction, BinaryOperator<R> binaryOperatorFunction){
return names.stream().map(mapFunction).reduce(binaryOperatorFunction).get();
}
public static <T,U,R> U filter4(List<T> names, U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> binaryOperatorFunction){
return names.stream().parallel().reduce(identity, accumulator, binaryOperatorFunction);
}
public static Optional<Double> inverse(Double t){
return null==t||t.equals(0) ? Optional.empty():Optional.of(1/t);
}
public static Optional<Double> square(Double t){
return null==t||t.equals(0) ? Optional.empty():Optional.of(Math.sqrt(t));
}
J2SE 8的Lambda --- functions的更多相关文章
- C++闭包: Lambda Functions in C++11
表达式无疑是C++11最激动人心的特性之一!它会使你编写的代码变得更优雅.更快速! 它实现了C++11对于支持闭包的支持.首先我们先看一下什么叫做闭包 维基百科上,对于闭包的解释是: In progr ...
- Python: Lambda Functions
1. 作用 快速创建匿名单行最小函数,对数据进行简单处理, 常常与 map(), reduce(), filter() 联合使用. 2. 与一般函数的不同 >>> def f (x) ...
- J2SE 8的Lambda --- 语法
语法例子 LambdaGrammarTest lambdaTest = new LambdaGrammarTest(); // 1. 能够推导出类型的,可以不写类型 String[] planets ...
- J2SE 8的Lambda --- Comparator
Person[] personArray = new Person[]{new Person("Tom"),new Person("Jack"),new Per ...
- fn project AWS Lambda 格式 functions
Creating Lambda Functions Creating Lambda functions is not much different than using regular funct ...
- 在Android中使用Java 8的lambda表达式
作为一名Java开发者,或许你时常因为缺乏闭包而产生许多的困扰.幸运的是:Java's 8th version introduced lambda functions给我们带来了好消息;然而,这咩有什 ...
- Python中Lambda, filter, reduce and map 的区别
Lambda, filter, reduce and map Lambda Operator Some like it, others hate it and many are afraid of t ...
- Php5.3的lambda函数以及closure(闭包)
从php5.3以后,php也可以使用lambda function(可能你会觉得是匿名函数,的确是但不仅仅是)来写类似javascript风格的代码: $myFunc = function() { e ...
- Automated EBS Snapshots using AWS Lambda & CloudWatch
Overview In this post, we'll cover how to automate EBS snapshots for your AWS infrastructure using L ...
随机推荐
- redash docker 运行
redash .superset .metabase 都是很不错的数据分析工具,支持多种数据源,同时可以方便的生成报表 基本上都支持定制化报表界面.通知(定时),metabase 有点偏产品,supe ...
- Where is Silverlight now?
Some time ago, I wrote an article about the comparison between HTML5 and Silverlight. That article w ...
- 如何彻底卸载Jenkins(Windows版本)
起因: 最近在做持续集成测试过程中遇到一个问题,之前部署的Jenkins管理员密码忘了之后无法登陆,而且删除掉tomcat下webapps文件夹中的Jenkins目录后,再次安装Jenkins后相关的 ...
- 海思3518EV200 SDK中获取和保存H.264码流详解
/****************************************** step 2: Start to get streams of each channel. ********** ...
- PHP 7.0 EOL (PHP 技术支持相关)
PHP 7.0 EOL (PHP 支持相关) PHP 5.6 于 2018-12-31 结束(EOL) 从图表看出,PHP 7.0 是一个过渡版本,现在已经 EOL. 而 PHP 7.1 将于明年年底 ...
- VS2015 C#项目工程配置emgucv依赖的方法
1.VS2015新建一个C# console工程 2.Tools->NuGet package management->manage NuGet package for solution- ...
- C/C++基础----表达式
1 基本概念 类型转换,小整型通常会被提升. 运算符重载,运算对象的个数.运算符的优先级和结合律都是无法改变的. 左值右值,对象被用做右值时,使用的是对象的值(内容):用做左值时,使用的是对象的身份( ...
- 【ActiveMQ入门-5】ActiveMQ学习-Queue与Topic的比较
Queue与Topic的比较 1.JMS Queue执行load balancer语义: 一条消息仅能被一个consumer收到. 如果在message发送的时候没有可用的consumer,那么它将被 ...
- bzoj 3413: 匹配
Description Input 第一行包含一个整数n(≤100000). 第二行是长度为n的由0到9组成的字符串. 第三行是一个整数m. 接下来m≤5·10^4行,第i行是一个由0到9组成的字符串 ...
- C++基本规则
C++ 程序结构 让我们看一段简单的代码,可以输出单词 Hello World. #include <iostream> using namespace std; // main() 是程 ...