[the road to full stack] top ten new features of JAVA basic course 11 JDK8 (20190706v1.2)

Keywords: Java Lambda jvm

Welcome to JAVA basic course

Blog address: https://blog.csdn.net/houjiyu...
This series of articles will mainly focus on some basic knowledge points of JAVA, which are summarized in ordinary times. No matter you are new to JAVA development rookie or senior people in the industry, you hope to bring some help to your peers. If you have any questions, please leave a message or add QQ: 243042162.

Message:
Everyone has potential energy, but it is easy to be covered by habits, lost by time, and consumed by inertia.

Ten new features

1.Lambda expression

public class JDK8_features {
    
    public List<Integer> list = Lists.newArrayList(1,2,3,4,5,6,7,8,9,10);
    
    /**
     * 1.Lambda Expression
     */
    @Test
    public void testLambda(){
        list.forEach(System.out::println);
        list.forEach(e -> System.out.println("Mode two:"+e));
    }
}

2.Stream functional operation flow element set

/**
     * 2.Stream Functional operation flow element set
     */
    @Test
    public void testStream(){
        List<Integer> nums = Lists.newArrayList(1,1,null,2,3,4,null,5,6,7,8,9,10);
        System.out.println("Summation:"+nums
                .stream()//Turn to Stream
                .filter(team -> team!=null)//filter
                .distinct()//Duplicate removal
                .mapToInt(num->num*2)//map operation
                .skip(2)//Skip the first 2 elements
                .limit(4)//Limit the first 4 elements
                .peek(System.out::println)//Streaming object functions
                .sum());//
    }

3. Add interface: default method and static method

 /**
     * 3.Interface addition: default method and static method
     *  default The default implementation method of the interface is to let the collection class implement these functional processing by default without modifying the existing code.
     *  (List Inherited from Iterable < T >, interface default method does not have to implement default forEach method)
     */
    @Test
    public void testDefaultFunctionInterface(){
        //You can directly use the interface name. Static method to access the static method in the interface
        JDK8Interface1.staticMethod();
        //The default method in an interface must be called through its implementation class
        new JDK8InterfaceImpl1().defaultMethod();
        //Multiple implementation classes, which must be copied when the default method has the same name
        new JDK8InterfaceImpl2().defaultMethod();
    }
     public class JDK8InterfaceImpl1 implements JDK8Interface1 {
        //After implementing the interface, because the default method is not an abstract method, it can be overridden or not!
//        @Override
//        public void defaultMethod(){
//            System.out.println("default method in interface");
//        }
    }
    
    public class JDK8InterfaceImpl2 implements JDK8Interface1,JDK8Interface2 {
        //After the interface is implemented, the default method name is the same, and the default method must be copied.
        @Override
        public void defaultMethod() {
            //Interface
            JDK8Interface1.super.defaultMethod();
            System.out.println("Implementation class replication name default method!!!!");
        }
    }

4. Method reference, used in combination with Lambda expression

    @Test
    public void testMethodReference(){
        //Constructor reference. The syntax is Class::new, or more general class < T >:: new. The constructor method is required to have no parameters.
        final Car car = Car.create( Car::new );
        final List< Car > cars = Arrays.asList( car );
        //Static method reference. The syntax is Class:: static Fu method, which requires to accept a Class type parameter.
        cars.forEach( Car::collide );
        //Method reference of any object. Its syntax is Class::method. No parameters, all elements call;
        cars.forEach( Car::repair );
        //Method reference of a specific object. Its syntax is instance::method. With parameters, call methods on an object and pass in list elements as parameters;
        final Car police = Car.create( Car::new );
        cars.forEach( police::follow );
    }
    
    public static class Car {
        public static Car create( final Supplier< Car > supplier ) {
            return supplier.get();
        }              
             
        public static void collide( final Car car ) {
            System.out.println( "Static method reference " + car.toString() );
        }
             
        public void repair() {   
            System.out.println( "Method reference of any object " + this.toString() );
        }
        
        public void follow( final Car car ) {
            System.out.println( "Method references for specific objects " + car.toString() );
        }
    }

5. Introduce duplicate notes

     @Test
    public void RepeatingAnnotations(){
        RepeatingAnnotations.main(null);
    }

6. Type notes

 @Test
    public void ElementType(){
        Annotations.main(null);
    }
    

7. Latest Date/Time API (JSR 310)

 @Test
    public void DateTime(){
        //1.Clock
        final Clock clock = Clock.systemUTC();
        System.out.println( clock.instant() );
        System.out.println( clock.millis() );
        
        //2. Date part in iso-8601 format without time zone information
        final LocalDate date = LocalDate.now();
        final LocalDate dateFromClock = LocalDate.now( clock );
                 
        System.out.println( date );
        System.out.println( dateFromClock );
                 
        // Time part of ISO-8601 format without time zone information
        final LocalTime time = LocalTime.now();
        final LocalTime timeFromClock = LocalTime.now( clock );
                 
        System.out.println( time );
        System.out.println( timeFromClock );
        
        // 3. Date and time without time zone information in iso-8601 format
        final LocalDateTime datetime = LocalDateTime.now();
        final LocalDateTime datetimeFromClock = LocalDateTime.now( clock );
                 
        System.out.println( datetime );
        System.out.println( datetimeFromClock );
        
        // 4. Date / time in a specific time zone,
        final ZonedDateTime zonedDatetime = ZonedDateTime.now();
        final ZonedDateTime zonedDatetimeFromClock = ZonedDateTime.now( clock );
        final ZonedDateTime zonedDatetimeFromZone = ZonedDateTime.now( ZoneId.of( "America/Los_Angeles" ) );
                 
        System.out.println( zonedDatetime );
        System.out.println( zonedDatetimeFromClock );
        System.out.println( zonedDatetimeFromZone );
        
        //5. A period of time in seconds and nanoseconds
        final LocalDateTime from = LocalDateTime.of( 2014, Month.APRIL, 16, 0, 0, 0 );
        final LocalDateTime to = LocalDateTime.of( 2015, Month.APRIL, 16, 23, 59, 59 );
         
        final Duration duration = Duration.between( from, to );
        System.out.println( "Duration in days: " + duration.toDays() );
        System.out.println( "Duration in hours: " + duration.toHours() );
    }
    

8. Add base64 encryption and decryption API

 @Test
    public void testBase64(){
        final String text = "Is to test encryption and decryption!! abjdkhdkuasu!!@@@@";
        String encoded = Base64.getEncoder()
            .encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
        System.out.println("After encryption="+ encoded );
         
        final String decoded = new String( 
            Base64.getDecoder().decode( encoded ),
            StandardCharsets.UTF_8 );
        System.out.println( "After decryption="+decoded );
    }

9. Array parallel operation

 @Test
    public void testParallel(){
        long[] arrayOfLong = new long [ 20000 ];        
        //1. Random assignment to array
        Arrays.parallelSetAll( arrayOfLong, 
            index -> ThreadLocalRandom.current().nextInt( 1000000 ) );
        //2. Print out the top 10 elements
        Arrays.stream( arrayOfLong ).limit( 10 ).forEach( 
            i -> System.out.print( i + " " ) );
        System.out.println();
        //3. Array sorting
        Arrays.parallelSort( arrayOfLong );     
        //4. Print the first 10 elements after sorting
        Arrays.stream( arrayOfLong ).limit( 10 ).forEach( 
            i -> System.out.print( i + " " ) );
        System.out.println();
    }
    

10. The JVM's PermGen space was removed: it was replaced by the Metaspace (JEP 122) Metaspace

 @Test
    public void testMetaspace(){
        //-XX: initial space size of metaspacesize. When the value is reached, garbage collection will be triggered for type unloading, and GC will adjust the value.
        //-XX:MaxMetaspaceSize maximum space, no limit by default
        //-XX:MinMetaspaceFreeRatio: after GC, the minimum percentage of the remaining space capacity of Metaspace is reduced to the garbage collection caused by space allocation.
        //-XX:MaxMetaspaceFreeRatio: after GC, the percentage of the maximum remaining space capacity of Metaspace is reduced to garbage collection caused by free space.
    }

Reference website:
(1)https://www.cnblogs.com/suger...
(2)https://blog.csdn.net/xuspcsd...

Posted by jf3000 on Sat, 02 Nov 2019 05:35:39 -0700