Lambda Jdk8

Lambda is an anonymous function that focuses only on the argument list and method body. We can think of a Lambda expression as a piece of code that can be passed (passing code like data).

Type inference: Omit parameter types

Compare with inner classes

The inner class this keyword points to the inner class itself, and in Lambda this points to the class in which the Lambda is located

The Java compiler compiles lambda expressions into private methods of the class. This method is dynamically bound using Java 7’s Invokedynamic bytecode directive.

expression

Introduced -> new operator: argument list plus operand

(Parameters)->{expressions}Copy the code

Method references

Class name :: Method name

Functional interface (Usage requirements)

Use @functionalInterface annotations

An abstract method in an interface can only be one (functional interface)

Predicate

Java. Util. Function. The Predicate function interface, add logic to the API method, very suitable for filters

List<String> names=Arrays.asList("dx","wdt","zfb","wuguangyao","nihaoshiw")); Predicate<String> filter1 = str->str.length()>5; Predicate<String> filter2 = str->str.endsWith("yao"); // filter(names,(n)->((String)n).startsWith("d")); filter(names,filter2); names.stream().filter(filter1.and(filter2)) .forEach(System.out::println); } public static void filter(List<String> list, Predicate condition){ for(String str:list){ if(condition.test(str)){ System.out.println(str); }}}Copy the code

Runnable

Runnable t = ()-> System.out.println("hello");
        t.run();Copy the code

s

Collections

The root interface

sort

implements Comparable

The entity class implements the Comparable interface

public class Student implements Comparable<Student> {
~~~~
@Override
    public int compareTo(Student o) {
        return stuId.compareTo(o.getStuId());
    }Copy the code

Collections.sort(List,new Comparator())

Create a Comparator that implements the Comparator interface

Collections.sort(list, new Comparator<StudentNoSort>() { @Override public int compare(StudentNoSort o1, StudentNoSort o2) { return o1.getStuId().compareTo(o2.getStuId()); }});Copy the code

Stream

Using Jdk8 Stream is even simpler

List<StudentNoSort> streamList = list.stream()
                .filter(w -> w.getClass()==StudentNoSort.class)
                .sorted(((o1, o2) -> o1.getStuId().compareTo(o2.getStuId())))
                .collect(Collectors.toList());Copy the code

Stream

A Stream is not a collection element. It is not a data structure and does not hold data. It is about algorithms and calculations. In the original version of Iterator, the user could only explicitly traverse elements one by one and perform certain operations on them. In the advanced version of Stream, the user only needs to say what operation needs to be performed on the elements it contains, such as “filter out strings of length greater than 10”, “get the first letter of every string”, etc., and the Stream implicitly traverses internally and performs the corresponding data conversion.

The Stream composition

Get a data source → transform the data → perform the operation (return a new Stream object), which allows the operation to be arranged like a chain and become a pipe

Stream Source

Collections, arrays, I/O channels, generators, etc

Stream Operation

Intermediate

A stream can be followed by zero or more Intermediate operations. The main purpose is to open the stream, do some degree of data mapping/filtering, and then return a new stream to be used by the next operation.

collect

Create a List

filter

Filter: Sets for filtering operations

distinct

Set elements are de-duplicated

map

Perform operations on functions

reduce

Combination of elements

forEach

Traverse elements

limit

Limit the amount of data in the stream

sorted

Sorting uses the Comparator interface

march,allMatch,noneMatch,anyMatch

The predicate element is passed in, and the Boolean is returned

There are the following

SummaryStatistics (int), sum(int sum)

Terminal

A stream can only have one terminal operation. After this operation is performed, the stream is used as “light” and cannot be operated again.

To construct the Stream

Collections

Collections
List<String> list = Arrays.asList(strArray);
stream = list.stream();Copy the code

example:

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 12, 1, 1, 2, 3, 2, 432, 4, 32, 54, 3, 3));
        int sum = list.stream().map(x -> x * x)
                .reduce((x, y) -> x + y)
                .get();Copy the code

Traversal file (NIO +lambda)

Path start = filesystems.getdefault ().getPath("/home/dzou/ report/mod "); Files.walk(start) .filter(path -> path.toFile().isFile()) .filter(path -> path.toString().endsWith(".jpg")) .forEach(System.out::println);Copy the code

Time complexity

A Stream has a set of operation functions, and each conversion operation is to put the conversion function into this set, loop through the Stream corresponding set during the Terminal operation, and then execute all functions on each element

Parallel parallelStream

If we look at this code, the output is not sequential

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        numbers.parallelStream()
                .forEach(out::println);Copy the code

The underlying use of ForkJoinPool, as opposed to ThreadPoolExecutor, allows a thread to create a new task and suspend the current task, at which point the thread can select subtasks to execute in the queue