lambda

 // Java 8之前:
new Thread(new Runnable() {
    @Override
    public void run() {
    System.out.println("Before Java8, too much code for too little to do");
    }
}).start();
//Java 8方式:
new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();
使用()->代替Runnable匿名类
语法:
(params) -> expression
(params) -> statement
(params) -> { statements }
有参数时:
(int even, int odd) -> even + odd
2.事件监听
// Java 8之前:
JButton show =  new JButton("Show");
show.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    System.out.println("Event handling without lambda expression is boring");
    }
});
// Java 8方式:
show.addActionListener((e) -> {
    System.out.println("Light, Camera, Action !! Lambda expressions Rocks");
});
3.集合遍历
// Java 8之前:
List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
for (String feature : features) {
    System.out.println(feature);
}
// Java 8之后:
List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
features.forEach(n -> System.out.println(n));
-----------------------------------------------------------------------------------------------------
package com.demo; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @see 参考博客:http://blog.csdn.net/bitcarmanlee/article/details/70195403 * */ public class LambdaTest01 { /** * Stream和集合的区别: 1.Stream不会自己存储元素。元素储存在底层集合或者根据需要产生。 2.Stream操作符不会改变源对象。相反,它会返回一个持有结果的新的Stream。 3.Stream操作可能是延迟执行的,这意味着它们会等到需要结果的时候才执行 * * */ public static void main(String[] args) { LambdaTest01 lam01=new LambdaTest01(); //lambda方法测试匿名函数 //lam01.testLamRun(); //测试list集合 //lam01.testList(); //String[] arr=new String[]{"1","2","3","4"}; //lam01.testPrime(arr); lam01.testMap(); //lam01.testReduce(); //lam01.testFilter(); //lam01.callPredicate(); } /*** * 使用流来完成素数去重 * */ public void testPrime(String...str) { List<String> list=Arrays.asList(str); List<Integer> in=list.stream() .map(tmp->new Integer(tmp)) .filter(tmp->isPrime(tmp)) .distinct() .collect(Collectors.toList()); System.out.println("distinctPrimary result is: " + in); } public boolean isPrime(int n) { if(n < 2) return false; if(n == 2) return true; if(n%2==0) return false; for(int i = 3; i*i <= n; i += 2) if(n%i == 0) return false; return true; } /** * 处理匿名函数 * */ public void testLamRun() { //1.8以前方式 new Thread(new Runnable() { @Override public void run() { System.out.println("--1.8以前方式--"); } }).start(); //lambda使用()->代替匿名函数的实现 new Thread(()->System.out.println("--lambda表达式测试--")).start(); } /** * 处理list集合 * */ public void testList() { List<String> list=new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); //jdk1.8以前方式 for(String tmp:list) { System.out.println("--集合元素--:"+tmp); } //lambda方式 list.forEach(tmp->{System.out.println("--lamdba-"+tmp);}); //另一种迭代,类似scala list.forEach(System.out::println); } /** * map测试 * map将一个对象转换成另外一个对象 * */ public void testMap() { List<Double> list=Arrays.asList(10.0,20.0,30.0); list.stream().map(x->x+x*0.5).forEach(System.out::println); //使用Person对象进行map测试 Person person=new Person("aa",11); //HashMap::new 新建一个HashMap对象 Map result=Stream.of(person).collect(HashMap::new,(map,p)->map.put(p.name,p.age),Map::putAll); //Collectors.toMap方法的第三个参数为键值重复处理策略,如果不传入第三个参数,当有相同的键时,会抛出一个IlleageStateException Map collecResult=Stream.of(person).collect(Collectors.toMap(p->p.name,p->p.age,(exsit,newv)->newv)); List<Map.Entry<String, Integer>> mapToList=new ArrayList<>(); mapToList.addAll(collecResult.entrySet()); mapToList.forEach(m->System.out.println(m.getKey()+"---"+m.getValue())); } /** * reduce()方法的处理方式一般是返回单个的结果值,每次都产生新的数据集 * collect()方法是在原数据集的基础上进行更新,过程中不产生新的数据集。 * 将多个对象合并成一个对象 * */ public void testReduce() { List<Double> list=Arrays.asList(10.0,20.0,30.0); double data=list.stream().map(x->x+x*0.05).reduce((sum,x)->sum+x).get(); System.out.println("--reduce-result-"+data); //以100为起始数,进行累加计算 int result=Stream.of(1, 2, 3, 4).reduce(100, (sum, item) -> sum + item); System.out.println("--result--"+result); result=Stream.of(1, 2, 3, 4).reduce(100, Integer::sum); System.out.println("--result-sum-"+result); } /** * filter * 过滤掉一部分数据 * */ public void testFilter() { List<Double> list=Arrays.asList(10.0,20.0,30.0,40.0); List<Double> resultList=list.stream().filter(x->x>20.0).collect(Collectors.toList()); //resultList.forEach(System.out::println); resultList.forEach(x->System.out.println(x)); } public void callPredicate() { List<String> list=Arrays.asList("Java","scala","phython","Shell","R"); System.out.println("---startWith---"); testPredicate(list, x->x.startsWith("J")); System.out.println("--endWith--"); testPredicate(list, x->x.endsWith("a")); System.out.println("---all-print-"); testPredicate(list, x->true); System.out.println("--none-ptint-"); testPredicate(list, x->false); System.out.println("--word more than 3--"); testPredicate(list, x->x.length()>4); } /** * Predicate 源自jdk8的java.util.function * 适用于过滤数据 * */ public void testPredicate(List<String> list,Predicate<String> condition) { //x->condition.test(x) 取出变量x然后根据condition进行比较 list.stream().filter(x->condition.test(x)).forEach(System.out::println); } } class Person { public String name; public int age; Person(String name,int age) { this.name=name; this.age=age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }











posted on 2018-03-06 18:10  xiaojiayu0011  阅读(191)  评论(0)    收藏  举报

导航