只会一点java

java持续学习者,每月一篇博客。罗列出技术栈,慢慢完善,持续学习,总有一天,你会追上甚至超越曾经的大神。
  博客园  :: 首页  :: 联系 :: 订阅 订阅  :: 管理

JDK8-十大新特性-附demo

Posted on 2017-04-17 13:20  只会一点java  阅读(37416)  评论(2编辑  收藏  举报

JDK9原计划17年上半年就发版,但未成功发版。才发现JDK8的特性还没总结过,特此总结。

一、十大特性

1.Lambda表达式

2.Stream函数式操作流元素集合

3.接口新增:默认方法与静态方法

4.方法引用,与Lambda表达式联合使用

5.引入重复注解

6.类型注解

7.最新的Date/Time API (JSR 310)

8.新增base64加解密API

9.数组并行(parallel)操作

10.JVM的PermGen空间被移除:取代它的是Metaspace(JEP 122)元空间

二、demo

demo基于junit可测。

  1 /**
  2  * 
  3  * @ClassName:JDK8_features
  4  * @Description:JDK8新特性
  5  * @author diandian.zhang
  6  * @date 2017年4月17日上午9:13:24
  7  */
  8 public class JDK8_features {
  9     
 10     public List<Integer> list = Lists.newArrayList(1,2,3,4,5,6,7,8,9,10);
 11     
 12     /**
 13      * 1.Lambda表达式
 14      */
 15     @Test
 16     public void testLambda(){
 17         list.forEach(System.out::println);
 18         list.forEach(e -> System.out.println("方式二:"+e));
 19     }
 20     
 21     /**
 22      * 2.Stream函数式操作流元素集合
 23      */
 24     @Test
 25     public void testStream(){
 26         List<Integer> nums = Lists.newArrayList(1,1,null,2,3,4,null,5,6,7,8,9,10);
 27         System.out.println("求和:"+nums
 28                 .stream()//转成Stream
 29                 .filter(team -> team!=null)//过滤
 30                 .distinct()//去重
 31                 .mapToInt(num->num*2)//map操作
 32                 .skip(2)//跳过前2个元素
 33                 .limit(4)//限制取前4个元素
 34                 .peek(System.out::println)//流式处理对象函数
 35                 .sum());//
 36     }
 37     
 38     /**
 39      * 3.接口新增:默认方法与静态方法
 40      *  default 接口默认实现方法是为了让集合类默认实现这些函数式处理,而不用修改现有代码
 41      *  (List继承于Iterable<T>,接口默认方法不必须实现default forEach方法)
 42      */
 43     @Test
 44     public void testDefaultFunctionInterface(){
 45         //可以直接使用接口名.静态方法来访问接口中的静态方法
 46         JDK8Interface1.staticMethod();
 47         //接口中的默认方法必须通过它的实现类来调用
 48         new JDK8InterfaceImpl1().defaultMethod();
 49         //多实现类,默认方法重名时必须复写
 50         new JDK8InterfaceImpl2().defaultMethod();
 51     }
 52     
 53     public class JDK8InterfaceImpl1 implements JDK8Interface1 {
 54         //实现接口后,因为默认方法不是抽象方法,重写/不重写都成!
 55 //        @Override
 56 //        public void defaultMethod(){
 57 //            System.out.println("接口中的默认方法");
 58 //        }
 59     }
 60     
 61     public class JDK8InterfaceImpl2 implements JDK8Interface1,JDK8Interface2 {
 62         //实现接口后,默认方法名相同,必须复写默认方法
 63         @Override
 64         public void defaultMethod() {
 65             //接口的
 66             JDK8Interface1.super.defaultMethod();
 67             System.out.println("实现类复写重名默认方法!!!!");
 68         }
 69     }
 70         
 71     /**
 72      * 4.方法引用,与Lambda表达式联合使用
 73      */
 74     @Test
 75     public void testMethodReference(){
 76         //构造器引用。语法是Class::new,或者更一般的Class< T >::new,要求构造器方法是没有参数;
 77         final Car car = Car.create( Car::new );
 78         final List< Car > cars = Arrays.asList( car );
 79         //静态方法引用。语法是Class::static_method,要求接受一个Class类型的参数;
 80         cars.forEach( Car::collide );
 81         //任意对象的方法引用。它的语法是Class::method。无参,所有元素调用;
 82         cars.forEach( Car::repair );
 83         //特定对象的方法引用,它的语法是instance::method。有参,在某个对象上调用方法,将列表元素作为参数传入;
 84         final Car police = Car.create( Car::new );
 85         cars.forEach( police::follow );
 86     }
 87     
 88     public static class Car {
 89         public static Car create( final Supplier< Car > supplier ) {
 90             return supplier.get();
 91         }              
 92              
 93         public static void collide( final Car car ) {
 94             System.out.println( "静态方法引用 " + car.toString() );
 95         }
 96              
 97         public void repair() {   
 98             System.out.println( "任意对象的方法引用 " + this.toString() );
 99         }
100         
101         public void follow( final Car car ) {
102             System.out.println( "特定对象的方法引用 " + car.toString() );
103         }
104     }
105     
106     /**
107      * 5.引入重复注解
108      * 1.@Repeatable 
109      * 2.可以不用以前的“注解容器”写法,直接写2次相同注解即可
110      * 
111      * Java 8在编译器层做了优化,相同注解会以集合的方式保存,因此底层的原理并没有变化。
112      */
113     @Test
114     public void RepeatingAnnotations(){
115         RepeatingAnnotations.main(null);
116     }
117     
118     /**
119      * 6.类型注解
120      * 新增类型注解:ElementType.TYPE_USE 和ElementType.TYPE_PARAMETER(在Target上)
121      * 
122      */
123     @Test
124     public void ElementType(){
125         Annotations.main(null);
126     }
127     
128     /**
129      * 7.最新的Date/Time API (JSR 310)
130      */
131     @Test
132     public void DateTime(){
133         //1.Clock
134         final Clock clock = Clock.systemUTC();
135         System.out.println( clock.instant() );
136         System.out.println( clock.millis() );
137         
138         //2. ISO-8601格式且无时区信息的日期部分
139         final LocalDate date = LocalDate.now();
140         final LocalDate dateFromClock = LocalDate.now( clock );
141                  
142         System.out.println( date );
143         System.out.println( dateFromClock );
144                  
145         // ISO-8601格式且无时区信息的时间部分
146         final LocalTime time = LocalTime.now();
147         final LocalTime timeFromClock = LocalTime.now( clock );
148                  
149         System.out.println( time );
150         System.out.println( timeFromClock );
151         
152         // 3.ISO-8601格式无时区信息的日期与时间
153         final LocalDateTime datetime = LocalDateTime.now();
154         final LocalDateTime datetimeFromClock = LocalDateTime.now( clock );
155                  
156         System.out.println( datetime );
157         System.out.println( datetimeFromClock );
158         
159         // 4.特定时区的日期/时间,
160         final ZonedDateTime zonedDatetime = ZonedDateTime.now();
161         final ZonedDateTime zonedDatetimeFromClock = ZonedDateTime.now( clock );
162         final ZonedDateTime zonedDatetimeFromZone = ZonedDateTime.now( ZoneId.of( "America/Los_Angeles" ) );
163                  
164         System.out.println( zonedDatetime );
165         System.out.println( zonedDatetimeFromClock );
166         System.out.println( zonedDatetimeFromZone );
167         
168         //5.在秒与纳秒级别上的一段时间
169         final LocalDateTime from = LocalDateTime.of( 2014, Month.APRIL, 16, 0, 0, 0 );
170         final LocalDateTime to = LocalDateTime.of( 2015, Month.APRIL, 16, 23, 59, 59 );
171          
172         final Duration duration = Duration.between( from, to );
173         System.out.println( "Duration in days: " + duration.toDays() );
174         System.out.println( "Duration in hours: " + duration.toHours() );
175     }
176     
177     /**
178      * 8.新增base64加解密API
179      */
180     @Test
181     public void testBase64(){
182         final String text = "就是要测试加解密!!abjdkhdkuasu!!@@@@";
183         String encoded = Base64.getEncoder()
184             .encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
185         System.out.println("加密后="+ encoded );
186          
187         final String decoded = new String( 
188             Base64.getDecoder().decode( encoded ),
189             StandardCharsets.UTF_8 );
190         System.out.println( "解密后="+decoded );
191     }
192     
193     /**
194      * 9.数组并行(parallel)操作
195      */
196     @Test
197     public void testParallel(){
198         long[] arrayOfLong = new long [ 20000 ];        
199         //1.给数组随机赋值
200         Arrays.parallelSetAll( arrayOfLong, 
201             index -> ThreadLocalRandom.current().nextInt( 1000000 ) );
202         //2.打印出前10个元素
203         Arrays.stream( arrayOfLong ).limit( 10 ).forEach( 
204             i -> System.out.print( i + " " ) );
205         System.out.println();
206         //3.数组排序
207         Arrays.parallelSort( arrayOfLong );     
208         //4.打印排序后的前10个元素
209         Arrays.stream( arrayOfLong ).limit( 10 ).forEach( 
210             i -> System.out.print( i + " " ) );
211         System.out.println();
212     }
213     
214     /**
215      * 10.JVM的PermGen空间被移除:取代它的是Metaspace(JEP 122)元空间
216      */
217     @Test
218     public void testMetaspace(){
219         //-XX:MetaspaceSize初始空间大小,达到该值就会触发垃圾收集进行类型卸载,同时GC会对该值进行调整
220         //-XX:MaxMetaspaceSize最大空间,默认是没有限制
221         //-XX:MinMetaspaceFreeRatio在GC之后,最小的Metaspace剩余空间容量的百分比,减少为分配空间所导致的垃圾收集
222         //-XX:MaxMetaspaceFreeRatio在GC之后,最大的Metaspace剩余空间容量的百分比,减少为释放空间所导致的垃圾收集
223     }
224     
225 }
引用到的相关类:
 1 public interface JDK8Interface1 {
 2 
 3     //1.接口中可以定义静态方法了
 4     public static void staticMethod(){
 5         System.out.println("接口中的静态方法");
 6     }
 7     
 8     //2.使用default之后就可以定义普通方法的方法体了
 9     public default void defaultMethod(){
10         System.out.println("接口中的默认方法");
11     }
12 }
13 
14 public interface JDK8Interface2 {
15 
16     //接口中可以定义静态方法了
17     public static void staticMethod(){
18         System.out.println("接口中的静态方法");
19     }
20     //使用default之后就可以定义普通方法的方法体了
21     public default void defaultMethod(){
22         System.out.println("接口中的默认方法");
23     }
24 }
25 
26 /**
27  * 
28  * @ClassName:RepeatingAnnotations
29  * @Description:重复注解@Repeatable
30  * @author diandian.zhang
31  * @date 2017年3月31日下午3:48:13
32  */
33 public class RepeatingAnnotations {
34     @Target( ElementType.TYPE )
35     @Retention( RetentionPolicy.RUNTIME )
36     public @interface Filters {
37         Filter[] value();
38     }
39      
40     @Target( ElementType.TYPE )
41     @Retention( RetentionPolicy.RUNTIME )
42     @Repeatable( Filters.class )
43     public @interface Filter {
44         String value();
45         String value2();
46     };
47      
48     @Filter( value="filter1",value2="111" )
49     @Filter( value="filter2", value2="222")
50     //@Filters({@Filter(  value="filter1",value2="111" ),@Filter(  value="filter2", value2="222")}).注意:JDK8之前:1.没有@Repeatable2.采用本行“注解容器”写法
51     public interface Filterable {        
52     }
53          
54     public static void main(String[] args) {
55         //获取注解后遍历打印值
56         for( Filter filter: Filterable.class.getAnnotationsByType( Filter.class ) ) {
57             System.out.println( filter.value() +filter.value2());
58         }
59     }
60 }
61 
62 /**
63  * 
64  * @ClassName:Annotations
65  * @Description:新增类型注解:ElementType.TYPE_USE 和ElementType.TYPE_PARAMETER(在Target上)
66  * @author diandian.zhang
67  * @date 2017年3月31日下午4:39:57
68  */
69 public class Annotations {
70     @Retention( RetentionPolicy.RUNTIME )
71     @Target( { ElementType.TYPE_USE, ElementType.TYPE_PARAMETER } )
72     public @interface NonEmpty {        
73     }
74          
75     public static class Holder< @NonEmpty T > extends @NonEmpty Object {
76         public void method() throws @NonEmpty Exception {           
77         }
78     }
79          
80     public static void main(String[] args) {
81         final Holder< String > holder = new @NonEmpty Holder< String >();       
82         @NonEmpty Collection< @NonEmpty String > strings = new ArrayList<>();       
83     }
84 }