首页 > 编程语言 > 详细

java8新特性

时间:2019-10-11 18:27:04      阅读:102      评论:0      收藏:0      [点我收藏+]

介绍流程:

Lambda表达式

Stream

Optional

 

附上思维导图:

技术分享图片

1.Lambda表达式

 (1)特点:通过表达式来实现相关接口方法,简化使用匿名类的操作,提高代码整洁性。

 (2):常见的几种使用方式:

 1 public class TestLambda {
 2     //常见形式
 3     private Math add = (a, b) -> a + b;
 4     private Math remove = (int a, int b) -> a - b;
 5     private Math decade = (a, b) -> a * b;
 6     private Math square = (int a, int b) -> a / b;
 7     private Message msg = (a) -> System.out.println("测试" + a);
 8     private Map map = new HashMap();
 9 
10     @Test
11     //测试
12     public void test() {
13         Integer[] i = new Integer[]{1, 2, 3, 4};
14         map.put(1, "x");
15         map.put(2, "y");
16         //通过表达式实现接口方法 ->有返回值
17         System.out.println(add.caculate(1, 2));
18         System.out.println(remove.caculate(1, 2));
19         System.out.println(decade.caculate(1, 2));
20         System.out.println(square.caculate(1, 2));
21         //无返回值
22         msg.play(1);
23         //集合的遍历 ->遍历所有值
24         map.forEach((c, v) -> System.out.println(v));
25         //集合的遍历 ->遍历所有键
26         map.forEach((c, v) -> System.out.println(c));
27         Arrays.asList(i).sort((a, b) -> {
28             if (a > b) {
29                 return a;
30             }
31             return b;
32         });
33     }
34 }
35 
36 //声明为函数式接口:仅包含一个方法,且方法符合Lambda表达式使用规范
37 @FunctionalInterface
38 interface Math {
39     int caculate(int a, int b);
40 }
41 
42 @FunctionalInterface
43 interface Message {
44     void play(int a);
45 }

效果截图:

技术分享图片

2.Stream

(1)特点:

(2)常用方法:

 

 1 public class TestStream {
 2     private List<String> list = new ArrayList<>();
 3 
 4     @Test
 5     public void test() {
 6         list.add(0, "123");
 7         list.add(1, "456");
 8         list.add(2, "789");
 9         list.add(3, "456");
10         //运用流Stream进行过滤,将内容不是123字符串的内容过滤出来并获得个数
11         System.out.println(list.stream().filter(e -> !e.equals("123")).count());
12         //集合遍历forEach
13         list.stream().forEach(e -> System.out.println(e));
14         //将过滤出来的元素再放入一个集合列表中
15         List l2 = (List) list.stream().filter(e -> !e.equals("123")).collect(Collectors.toList());
16         //遍历
17         l2.stream().forEach(e -> System.out.println(e));
18         //通过流stream获取新集合的首个Optional元素
19         System.out.println("首元素:" + l2.stream().findFirst());
20         //通过流Stream去重后元素个数
21         System.out.println("去重后个数为:" + l2.stream().distinct().count());
22     }
23 }

 

 

 

 

 

 

3.Optional

 

 

 

 

 

 

 

 

 

 

 

 

 

 

文章待完善。。。

java8新特性

原文:https://www.cnblogs.com/weekstart/p/java8.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!