Java8 new Features (iv) _stream detailed

Source: Internet
Author: User
Tags lua

Previously wrote an article with stream processing map, but there is no overall understanding of stream, this time combined with the concurrent programming network and the introduction of the stream in IBM a summary of the article, I will rewrite the list of processing, after all, the actual work of everyone daily use

Stream Simple Introduction definition
    • A sequence of elements supporting sequential and parallel aggregate operations.

    • Sequence of elements that support sequential parallel aggregation operations

Let's see how the gods interpret them.

You can think of stream as a premium version of iterator. The original version of the iterator, the user can only one one to traverse the element and perform certain operations on it; the advanced version of the stream, the user simply gives what they need to do with the elements they contain, such as "filter out strings longer than 10", "get the first letter of each string", etc. How exactly these actions are applied to each element, just give the stream a good

Simple demo Write a simple function of filtering null
    public static void main(String[] args) {        List arrys = Arrays.asList(1, null, 3, 4);        arrys.forEach(System.out::print);        System.out.println();        arrys = (List) arrys.stream()                .filter(num -> num != null)                .collect(Collectors.toList());        arrys.forEach(System.out::print);    }

Execution results

1null34134
Parsing code


1, create stream;
2, convert stream (processing data), each conversion of the original stream object does not change, return a new stream object ( can have multiple conversions );
3, the stream to the aggregation (Reduce) operation, to obtain the desired results;

Create stream

The most common way to create a stream is two ways:

    • Static Factory method via stream interface
    • Convert a collection object to stream via the default method –stream () of the collection interface (previously written article is based on this for map processing)
// 1. Individual valuesStream stream = Stream.of("a", "b", "c");// 2. ArraysString [] strArray = new String[] {"a", "b", "c"};stream = Stream.of(strArray);stream = Arrays.stream(strArray);// 3. Collections(实际工作中经常用到)List<String> list = Arrays.asList(strArray);stream = list.stream();
How to convert Stream method

Here is in fact commonly used to, mainly explain here, the picture here from the concurrent programming network, have to admire, the program is good, drawing is better than I

Distinct

Distinct: Deduplication for elements contained in stream (the Equals method to redirect logical dependency elements), with no duplicate elements in the newly generated stream;

Code Demo
    public static void main(String[] args) {        List<String> list = Arrays.asList("java---", "java---", "erlang---", "lua---", "lua---");        list.forEach(System.out::print);        System.out.println();        list = list.stream()                .distinct()                .collect(Collectors.toList());        list.forEach(System.out::print);    }

Results

java---java---erlang---lua---lua---java---erlang---lua---
Filter

Filter: The newly generated stream contains only the elements that meet the criteria for filtering the elements contained in the stream using a given filter function;

Code Demo
    public static void main(String[] args) {        List<String> list = Arrays.asList("java---", "java---", "erlang---", "lua---", "lua---");        list.forEach(System.out::print);        System.out.println();        list = list.stream()                .filter(e -> e.length() > 7)                .collect(Collectors.toList());        list.forEach(System.out::print);    }

Results

java---java---erlang---lua---lua---erlang---
Map

Map: Its role is to map each element of input stream into another element of the output stream.

Code Demo
    public static void main(String[] args) {        List<String> list = Arrays.asList("java---", "java---", "erlang---", "lua---", "lua---");        list.forEach(System.out::print);        System.out.println();        list = list.stream()                .map(String::toUpperCase)                .collect(Collectors.toList());        list.forEach(System.out::print);    }

Results

java---java---erlang---lua---lua---JAVA---JAVA---ERLANG---LUA---LUA---
Limit

Limit: Truncates a stream, obtains its first n elements, and obtains all its elements if the original stream contains fewer than n elements;

Code Demo
    public static void main(String[] args) {        List<String> list = Arrays.asList("java---", "java---", "erlang---", "lua---", "lua---");        list.forEach(System.out::print);        System.out.println();        list = list.stream()                .limit(3)                .collect(Collectors.toList());        list.forEach(System.out::print);    }

Results

java---java---erlang---lua---lua---java---java---erlang---
Skip

Skip: Returns a new stream with elements left behind when the first n elements of the original stream are discarded, and if the original stream contains fewer than n elements, the empty stream is returned;

Code Demo
    public static void main(String[] args) {        List<String> list = Arrays.asList("java---", "java---", "erlang---", "lua---", "lua---");        list.forEach(System.out::print);        System.out.println();        list = list.stream()                .skip(3)                .collect(Collectors.toList());        list.forEach(System.out::print);    }

Results

java---java---erlang---lua---lua---lua---lua---
FindFirst

FindFirst: It always returns the first element of a Stream, or null. The key here is its return value type: Optional

Code Demo
    public static void main(String[] args) {        List<String> list = Arrays.asList("java---", "java---", "erlang---", "lua---", "lua---");        list.forEach(System.out::print);        System.out.println();        Optional<String> first = list.stream()                .findFirst();        System.out.println(first.get());    }

Results

java---java---erlang---lua---lua---java---
Summarize

Of course, there are many ways, not described here, the use of real work often combined

This code, for example, is an example of a previous article filtering null values and empty strings in a map.

public static Map<String, Object> parseMapForFilterByOptional(Map<String, Object> map) {        return Optional.ofNullable(map).map(                (v) -> {                    Map params = v.entrySet().stream()                            .filter((e) -> checkValue(e.getValue()))                            .collect(Collectors.toMap(                                    (e) -> (String) e.getKey(),                                    (e) -> e.getValue()                            ));                    return params;                }        ).orElse(null);    }

In summary, the characteristics of Stream can be summed up as:

Not a data structure
    • It has no internal storage, it simply fetches the data from source (data structure, array, generator function, IO Channel) with the Operation pipeline.
    • It also never modifies the data of the underlying data structure that it encapsulates. For example, the filter operation of a stream produces a new stream that does not contain the filtered elements, rather than removing those elements from source.
    • All Stream operations must have a lambda expression as a parameter

Reference articles
-[1.] https://ifeve.com/stream/
-[2.] https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/

Java8 new Features (iv) _stream detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.