Article From:https://www.cnblogs.com/java-zhao/p/9061745.html

java84 important new features:

  • Lambda
  • Stream
  • Optional
  • Date time API
  • Interface method (default and static method, jdk9 can define private method).

1. Lambda

 1 import java.util.Comparator;
 2 import java.util.function.Consumer;
 3 
 4 /**
 5  * @author zhaojigang
 6  * @date 2018/5/19
 7  */
 8 public class LambdaTest {
 9     /**
10      * Lambda It is an anonymous function.11      * 1、grammar12      * LambdaThe expression introduces the operator as "->" and the operator divides Lambda into two parts.13      * Left side: all parameters required for Lambda expression are specified.14      * Right side: Specifies the Lambda body, which is the function that Lambda expression wants to perform.15      *
16      * 2、Examples17      */
18     public void testLambda() {
19         /**
20          * Grammatical formatting 1: no reference, no return value21          */
22         Runnable task = () -> System.out.println("hello lambda");
23         /**
24          * Grammatical format two: a parameter, no return value25          * Note: the parameter type can be passed through26          */
27         Consumer<String> consumer = str -> System.out.println(str);
28         /**
29          * Syntax format three: a parameter with a return value30          * Note: when the Lambda body has only one statement, omit braces and return.31          */
32         Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y);
33     }
34 
35     /**
36      * Functional interface: an interface that contains only one abstract method.37      * 1、The object of the interface can be created through the Lambda expression.38      * 2、You can use @FunctionalInterface annotation on any function interface, so that it can check whether it is a functional interface.39      *
40      * JavaFour core functional interfaces are built in:41      * 1、Consumer<T>:void accept(T t),Consumer interface42      * 2、Supplier<T>:T get(),Supply interface43      * 3、Function<T, R>:R apply(T t),Functional interface44      * 4、Predicate<T>:boolean test(T t),Assertion interface45      * There is also a part of the sub interface.46      */
47     public void testFunctionalInterface() {
48         Consumer<String> consumer = str -> System.out.println(str);
49     }
50 }

 

Two, Stream

  1 import java.util.ArrayList;
  2 import java.util.HashMap;
  3 import java.util.List;
  4 import java.util.Map;
  5 import java.util.Optional;
  6 import java.util.OptionalLong;
  7 import java.util.stream.LongStream;
  8 
  9 /**
 10  * @author zhaojigang
 11  * @date 2018/5/19
 12  */
 13 public class StreamTest {
 14 
 15     static List<Integer> integerList = new ArrayList<Integer>() {{
 16         add(1);
 17         add(2);
 18         add(3);
 19         add(4);
 20         add(5);
 21         add(5);
 22         add(5);
 23     }};
 24 
 25     static List<Integer> integerList2 = new ArrayList<Integer>() {{
 26         add(10);
 27         add(20);
 28         add(30);
 29     }};
 30 
 31     static Map<String, List<Integer>> map1 = new HashMap<>();
 32 
 33     static {
 34         map1.put("list1", integerList);
 35         map1.put("list2", integerList2);
 36     }
 37 
 38     /**
 39      * Segmentation and screening 40      */
 41     public static void test1() {
 42         integerList.stream()
 43                 .filter(x -> x > 2) // 3,4,5,5,5
 44                 .skip(2) //5,5,5
 45                 .limit(2) //5,5 Short circuit: once you get 2 elements, do not iterate backwards.
 46                 .distinct() //5
 47                 .forEach(System.out::println);
 48     }
 49 
 50     /**
 51      * mapping 52      * map(Function f):Taking a function as a parameter, the function is applied to each element and is mapped to a new element. 53      * flatMap(Function f):A function is taken as a parameter to change every value in the stream to another stream, and then connect all the streams into one stream. 54      */
 55     public static void test2() {
 56         integerList.stream()
 57                 .map(x -> x + 10)
 58                 .forEach(System.out::println);
 59 
 60         map1.values().stream()
 61                 .flatMap(x -> x.stream()) // xIt is every List, flatMap that merges the Stream of every List.
 62                 .forEach(System.out::println);
 63 
 64     }
 65 
 66     /**
 67      * sort 68      * sorted():Generate a new stream, which is sorted in natural order (according to the Comparable interface of the element). 69      * sorted(Comparator comp):A new flow is generated, which is sorted sequentially in the comparator (according to the custom Comparator). 70      */
 71     public static void test3() {
 72         integerList.stream()
 73                 .sorted()
 74                 .forEach(System.out::println);
 75 
 76         integerList.stream()
 77                 .sorted((x, y) -> {
 78                     if (x < y) {
 79                         return 1;
 80                     } else {
 81                         return -1;
 82                     }
 83                 })
 84                 .forEach(System.out::println);
 85 
 86     }
 87 
 88     /**
 89      * Lookup and match 90      * allMatch(Predicate p):Check to see if all the elements are matched 91      * anyMatch(Predicate p):Check to see if at least one element is matched 92      * noneMatch(Predicate p):Check whether all elements are not matched 93      * findFirst():Return to the first element 94      * findAny():Return any element in the current stream 95      * count():Return the total number of elements in the flow 96      * max(Comparator c):Return the maximum value in the flow 97      * min(Comparator c):Return the minimum value in the flow 98      */
 99     public static void test4() {
100         final boolean allMatch = integerList.stream().allMatch(x -> x > 4);
101         final boolean anyMatch = integerList.stream().anyMatch(x -> x > 4);
102         final boolean noneMatch = integerList.stream().noneMatch(x -> x > 4);
103         final Optional<Integer> first = integerList.stream().filter(x -> x > 3).findFirst();
104         final Optional<Integer> any = integerList.stream().filter(x -> x > 3).findAny();
105         final long count = integerList.stream().filter(x -> x > 4).count();
106         final Optional<Integer> max = integerList.stream()
107                 .max((x, y) -> {
108                     if (x < y) {
109                         return 1;
110                     } else {
111                         return -1;
112                     }
113                 });
114 
115     }
116 
117     /**
118      * Statute119      * <p>
120      * reduce(T iden, BinaryOperator b):The elements in the flow can be combined repeatedly to get a value. Return to T, where iden is the initial value121      * reduce(BinaryOperator b):The elements in the flow can be combined repeatedly to get a value. Return to Optional< T>122      */
123     public static void test5() {
124         // Calculation: 100+1+2+3+4+5+5+5
125         final Integer sum = integerList.stream().reduce(100, (x, y) -> x + y);
126         final Optional<Integer> sumOptional = integerList.stream().reduce((x, y) -> x + y);
127     }
128 
129     /**
130      * collect131      * Commonly used:132      * 1、Collect the stream elements to List:List< Employee> emps= list.stream ().Collect (Collectors.toList ());133      * 2、Collect the stream elements to Set:List< Employee> emps= list.stream ().Collect (Collectors.toSet ());134      * 3、Each string in the connection stream: String str= list.stream ().Map (Employee:: getName).Collect (Collectors.joining ());135      * 4、Grouping: Map< Emp.Status, List< Emp> > map= list.stream ().Collect (Collectors.groupingBy (Employee)::: getStatus));136      *
137      * Not commonly used:138      * 1、Zoning according to true or false: Map< Boolean, List< Emp> > vd= list.stream ().Collect (Collectors.partitioning)By (Employee:: getManage));139      * 2、The maximum value is selected according to the comparator: Optional< Emp> max= list.stream ().Collect (Collectors.maxBy (comparingInt) (Employee:: get).Salary))))140      * 3、The minimum value is selected according to the comparator: Optional< Emp> min = list.stream ().Collect (Collectors.minBy (comparingInt) (Employee:: G).EtSalary))))141      * 4、Collect the stream elements to any specified set: Collection< Employee> emps=list.stream ().Collect (Collectors.toCollection (ArrayLis).T:: new));142      * 5、Calculate the number of elements in the flow: long count = list.stream ().Collect (Collectors.counting ());143      * 6、The summation of the properties of elements in convection: int total=list.stream ().Collect (Collectors.summingInt (Employee:: getSalary));144      * 7、The average value of the Integer attribute in the flow is calculated: double avg= list.stream ().Collect (Collectors.averagingInt (Employee:: getSalary)).
145      */
146     public static void test6() {
147     }
148 
149     /**
150      * Parallel flow and serial flow151      * Parallel flow is to divide a content into multiple data blocks and to process the flow of each block separately with different threads.152      * Bottom: fork/join153      * Stream APIIt is possible to switch between parallel flows and sequential streams by parallel () and sequential ().154      */
155     public static void test7(){
156         long start = System.currentTimeMillis();
157 
158         final OptionalLong sum = LongStream.rangeClosed(0, 100000000000L)
159                 .parallel()
160                 .reduce(Long::sum);
161 
162         System.out.println(sum + "-" + (System.currentTimeMillis() - start));
163     }
164 
165     public static void main(String[] args) {
166         test7();
167     }
168 }

 

Three, Optional

 1 import java.util.Optional;
 2 
 3 /**
 4  * @author zhaojigang
 5  * @date 2018/5/19
 6  */
 7 public class OptionalTest {
 8 
 9     public static void main(String[] args) {
10 //        String godName = "shijia";
11         String godName = null;
12         // Common methods
13         final String god = Optional.ofNullable(godName).orElse("yesu");
14         System.out.println(god);
15     }
16 }

 

Four, date API

 1 import java.time.Duration;
 2 import java.time.Instant;
 3 import java.time.LocalDateTime;
 4 import java.time.format.DateTimeFormatter;
 5 
 6 /**
 7  * @author zhaojigang
 8  * @date 2018/5/19
 9  */
10 public class TimeTest {
11 
12     /**
13      * 1. Date creation:14      * LocalDate localDate = LocalDate.now();
15      * LocalTime localTime = LocalTime.now();
16      * LocalDateTime localDateTime = LocalDateTime.now();
17      *
18      * LocalDate localDate = LocalDate.of(2016, 10, 26);
19      * LocalTime localTime = LocalTime.of(02, 22, 56);
20      * LocalDateTime localDateTime = LocalDateTime.of(2016, 10, 26, 12, 10, 55);
21      *
22      * Two, date addition and subtraction23      * plusDays, plusWeeks, plusMonths, plusYears
24      * minusDays, minusWeeks, minusMonths, minusYears
25      * plus, minus
26      *
27      * Three, date comparison calculation28      * isBefore, isAfter
29      *
30      * Four. Is it a leap year31      * isLeapYear
32      *
33      * Five, time stamp and time interval operation34      * Instant Timestamp: the operation described in the first year of Unix (traditionally set at midnight on January 1, 1970 UTC).35      * Duration:For calculating two "time" intervals36      * Period:Used to calculate two "date" intervals37      *
38      * Six, time corrector39      * TemporalAdjuster/TemporalAdjusters Adjust time: for example, get the next Sunday, for example40      *
41      * Seven, date analysis and formatting42      * java.time.format.DateTimeFormatterclass43      */
44     public static void main(String[] args) {
45         /**
46          * Computational time interval47          */
48         Instant in1 = Instant.now();
49         Instant in2 = Instant.now();
50         System.out.println(Duration.between(in1, in2).toMillis());
51 
52         /**
53          * DateFormatter54          */
55         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
56         LocalDateTime time1 = LocalDateTime.now();
57         String formatDateTime = time1.format(formatter);
58 
59         /**
60          * Date parsing61          */
62         LocalDateTime dateTime = LocalDateTime.parse(formatDateTime, formatter);
63     }
64 }

We usually use the Apache commons package for date operations, but this will introduce a package that can use Java itself, which is java itself.

 

Five. Interface method

 1 /**
 2  * @author zhaojigang
 3  * @date 2018/5/19
 4  */
 5 public class InterfaceTest {
 6     public static void main(String[] args) {
 7         MyImpl myClass = new MyImpl();
 8         System.out.println(myClass.getName());
 9         System.out.println(MyInterface.getAge());
10     }
11 }
12 
13 interface MyInterface {
14     default String getName(){
15         return "nana";
16     }
17 
18     static Integer getAge(){
19         return 18;
20     }
21 }
22 
23 /**
24  * If a default method is defined in an interface, and a method with the same name is defined in another parent class, the parent class is taken.25  * If a default method is defined in an interface, and another method of the same name is defined in the other implementation interface, the implementation class needs to rewrite one of them26  */
27 class MyImpl implements MyInterface {
28 }

In jdk9, the private method can be defined in the interface.

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *