Java8 - Lambda和Stream

1 Introduction

This paper describes Java8 of 2 large main new features of lambda expressions and Stream API, 2 to provide a higher level of abstraction, simplify development, increase productivity.

2. Lambda expressions

2.1 Lambda expressions acquaintance

Create a thread, using an Runnableanonymous inner class

Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello Aron.");
            }
        });

  

Looking at the problem is not, in fact, quite obvious drawbacks: Too many template syntax, the real meaning of the statement only business System.out.println("Hello Aron."), and as such, we are also seriously interfere with the reading code.

The introduction of lambdathe expression, you can write

Thread thread = new Thread(() -> System.out.println("Hello Aron."));

 

2. Stream flow

2.1 Introduction

Stream (Stream) is a new feature Java8, and allows programmers to a set of operating from a higher level of abstraction. On the idea, similar to SQL stored procedures, there are several steps:

  1. Define some operations collection Note: This only defines, not really perform
  2. Trigger execution, get results
  3. The results of further processing, screening, print, use

Among them, the first step of the custom action is called lazy evaluation, give you routine (to return Stream), but does not perform return results.

Step 2 trigger operation called eager evaluation, this man went ahead and flew to the result (return result data).

Step 3 screening SQL-like whereclauses, further filter the results.

2.2 Stream API

Stream Class is in java.util.streamthe package, is one of Java8 core classes, with many methods, the following lists some of the more important ways to explain. More is initiate any course can not match their perception is more straightforward, first find the feeling, try to master the basic usage to use, and slowly will naturally up.

2.2.1 Stream.of(T… t)

To use Stream, it would have to first create a Stringtype ofStream

Stream<String> StrStream = Stream.of("a", "b");

2.2.2 Stream.collect(Collector<? super T, A, R> collector)

Use collectors Collectorwill StrStreambe converted to the familiar collectionCollection

List<String> collect = StrStream.collect(Collectors.toList());


2.2.3 Stream.map(Function<? super T, ? extends R> mapper)

The so-called map, from the literal understanding is mapped. This refers to the object-relational mapping,

Collection mapping from object to such properties in combination:

List<String> names = Stream.of(new Student("zhangSan"), new Student("liSi")) .map(student -> student.getName()) .collect(toList());

From lowercase letters are mapped to uppercase letters:

List<String> collected = Stream.of("a", "b", "hello") .map(string -> string.toUpperCase()) .collect(toList());

String flow stream into a string array in accordance with the space

Stream<String> stringStream = Stream.of("Hello Aron.");
Stream<String[]> stringArrayStream = stringStream.map(word -> word.split(" "));
 

2.2.4 Stream.filter(Predicate<? super T> predicate)

filterAs the name suggests, filter screening. Where the interface is a function of the parameter condition satisfying the condition of the selected element

// screening of students older than 19 
List <Student> STU = Stream.of (new new Student ( "zhangsan", 19), new new Student ( "LiSi"), 20) 
                        .filter (Student -> student.getAge ()> . 19) 
                        .collect (toList ());

 

2.2.5 Stream.flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)

flatMapFlat mapping, i.e. an array of data elements Streaminto a single element

Stream <String> Stream.of stringstream = (. "Aron the Hello"); 
// return value is an array 
Stream <String []> = stringArrayStream stringStream.map (Word -> word.split ( "")); 
// flatMap after flattening mapping elements incorporated 
Stream <String> flatResult = stringArrayStream.flatMap ( arr -> Arrays.stream (arr))

2.2.6 Stream.max(Comparator<? super T> comparator)

maxThat is maximum, similar to SQLthe function of max(), data from the selected value in accordance with the most certain conditions

// screening oldest / small student 
Stream <Student> studentStream = Stream.of (new new Student ( "zhangSam", 19), new new Student ( "LiSi", 20)); 
Optional <Student> max = studentStream.max ( Comparator.comparing (student -> student.getAge ())); 
// Optional <student> max = studentStream.min (Comparator.comparing (student -> student.getAge ())); 
// maximum age / small student 
Student student = max.get ();

 

2.2.7 Sream.reduce(T identity, BinaryOperator<T> binaryOperator)

reduceGenerating a value from the operation to achieve a set of values, above max, minare actually reduceoperating.

Parameter Identity represents the initial value,

Parameter binaryOperatoris a function interface, represents a binary operator, it can be used for mathematical operation

// Use reduce () summed (not recommended for production environments) 
int Stream.of COUNT = (. 1, 2,. 3) .reduce (0, (ACC, Element) -> Element + ACC);

The above code, expand reduce() operation

BinaryOperator<Integer> accumulator = (acc, element) -> acc + element;
int count = accumulator.apply( accumulator.apply(accumulator.apply(0, 1),2), 3);

2.2.8 Integrated Operation

// Find classmates dictionary sort order and press all surnamed Zhang, stored List 
List <Student> newList = studentList.Stream () 
            .filter (Student -.> Student.getName () startsWith ( "Zhang")) 
            .sorted ( Comparator.comparing (Student -> student.getName ()) 
            .collect (toList ());

  

 

 







Guess you like

Origin www.cnblogs.com/jiehanshi/p/12125677.html