JDK8 lameda表达式学习例子

时间:2021-12-26 19:49:55
lameda表达式是jdk8出的内容,作为一名老程序员,一直没接触。二次开发git上的一个开源项目,直接泪崩。于是赶紧补补课,直接上学习过程中的源码:
package xx.test.lameda; import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate; public class LamedaMain {
public static void main(String[] args) { List<String> list= Arrays.asList("danny","fancial","join","jack1");      // 创建过滤条件 Predicate可支持and、or、xor组合
Predicate<String> predicate = (n)->n.startsWith("j");
Predicate<String> predicate1 = (n)->n.length()==5;      //过滤list中字母“j”开头的元素
System.out.println("====print start with j");
list.stream().filter(predicate).forEach(System.out::println);      //过滤list中字节长度为5的元素
System.out.println("=====print length is 5");
list.stream().filter(predicate1).forEach(System.out::println); //过滤list中字母“j”开头并且长度为5的元素
System.out.println("=======print start with j and length is 5");
list.stream().filter(predicate.and(predicate1)).forEach(System.out::println); //过滤list中字母“j”开头或者长度为5的元素
System.out.println("=======print start with j or length is 5");
list.stream().filter(predicate.or(predicate1)).forEach(System.out::println); //利用stream和map修改doubleList中元素的内容
System.out.println("=======show may operation");
List<Double> doubleList = Arrays.asList(100.0,200.0,300.0,400.0);
doubleList.stream().map(n->n*0.2).forEach(System.out::println); //利用stream和reduce聚合输出
System.out.println("========show reduce operation");
System.out.println("sum is "+doubleList.stream().map(n->n*0.2).reduce((sum,n)->sum+n).get()); List<Integer> integerList = Arrays.asList(100,200,300,400);
System.out.println("max is "+integerList.stream().reduce(Integer::max).get());
System.out.println("min is "+integerList.stream().reduce(Integer::min).get()); System.out.println("sum is "+integerList.stream().reduce(Integer::sum).get());
}
}