Introduction to JAVA8 Stream flow operation

Source: Internet
Author: User

Flow operation in my contact with the part, is to deal with the collection container collection, add stream operation is mainly for functional programming, to a large extent, can simplify the code

Concise Code handling complex logic This is the pursuit of every program ape, nonsense not much said, began to introduce

Basic steps for using the stream

1. Create stream;
2. Convert stream, each conversion of the original stream object does not change, return a new Stream object (* * can have multiple conversions *);
3. The stream for aggregation (Reduce) operation, to obtain the desired results;

Stream Creation

Lists is a tool class in guava
list<integer> nums = lists.newarraylist (1,null,3,4,null,6);
Nums.stream (). filter (num-> num!= null). Count ();
<pre name= "code" class= "Java" >/**
of method: There are two overload methods, one accepts variable length parameter, one interface single value
* * *
stream<integer> Integerstream = Stream.of (1, 2, 3, 5);
stream<string> StringStream = Stream.of ("Taobao");
/**
Generator method: Generates an infinite length Stream whose elements are generated by a given Supplier
/stream.generate (New supplier<double> ( {
   	@Override public
   	Double get () {return
		math.random ();
	}
});
Stream.generate (()-> math.random ());
Stream.generate (math::random);
   
/**
Iterate method: Also generates an infinite length of the stream, and unlike generator, its elements are generated repeatedly by invoking a user-specified function on a given seed value (seed)
. The elements included can be considered: seed
/stream.iterate (1, item-> Item + 1). Limit. ForEach (system.out::p rintln);


All collection classes can call the stream () method directly to return a stream object

This is shown in the first example of this article to get its corresponding stream object from the list object, and if you look at Java doc, you can see that the collection interface has a stream method, so all of its subclasses can get the corresponding stream object.

Public interface Collection<e> extends iterable<e> {
    //other method omits
	default stream<e> Stream () { Return
        Streamsupport.stream (Spliterator (), false);
    }
Convert Stream
The conversion stream method has a very good processing method, here all introduction, introduction several, the other methods of use are almost

1. Distinct: For the elements contained in the stream to redo (to the logical dependent elements of the Equals method), the newly generated stream has no duplicate elements;

list<string> list = arrays.aslist ("AA", "BB", "CC", "a", "B", "C", "AA", "AB", "cc", "BB", "BC");
List = List.stream (). Distinct (). Collect (Collectors.tolist ()); [AA, BB, CC, A, B, C, AB, BC]

2. Filter: For the elements contained in the stream using the given filter function for filtering operations, the newly generated stream contains only the elements that meet the criteria

list<string> list = arrays.aslist ("AA", "BB", "CC", "a", "B", "C", "a", "AA", "AB", "cc", "BB", "BC");
List.stream (). Filter (e-> e.length () >=2). ForEach (e-> System.out.print (E + ","));
AA,BB,CC,AA,AB,CC,BB,BC,


3. Map: For the elements contained in the stream using the given transformation function for the conversion operation, the newly generated stream contains only the elements that the transformation generates. This method has three variants for the original type, respectively: Maptoint,maptolong and maptodouble. These three methods are also better understood, such as Maptoint is to convert the original stream into a new stream, and the elements in the newly generated stream are of type int. There are three variants that can eliminate the extra cost of automatic boxing/unboxing;

<pre name= "code" class= "java" >List<Integer> integerlist = arrays.aslist (1, 2, 3, 8, 9, 6, 4, 2, 3, 7, 6);
Integerlist.stream (). Map (Var-> {var + +; var = 2; return var;}). ForEach (System.out::p rint);

Doublestream Doublestream = Integerlist.stream (). Maptodouble ((value)-> value * 1.0);

4. Flatmap: And map Similar, the difference is that each element of its conversion to get the stream object, will be the target stream elements compressed into the parent set;

List<integer> together = Stream.of (Aslist (1, 2), Aslist (3, 4)). Flatmap (Numbers-> numbers.stream ()). Collect ( ToList ());
This method can be used to convert a two queue into a stream when it is processed together

The code in the upper section can be simplified to

List<integer> together = Stream.of (Arrays.aslist (1, 2), Arrays.aslist (3, 4))
                . Flatmap (Collection::stream). Collect (Collectors.tolist ());
5. Peek: Generates a new stream that contains all the elements of the original stream, and provides a consumption function (consumer instance) that executes the given consumption function when each element of the new stream is consumed;
This method does not change the form of elements in the stream, primarily for debugging or output.

List.stream (). DISTINCT (). Peek (e-> System.out.println (E.length ())). Count ();
When lambda expressions are used in the Peek () method, the return value can only be a void type


method to briefly introduce only a few of the remaining and limit () Skip () ForEach (), etc.

Aggregation (Reduce) operation

The following is a two-part introduction to the convergence operation:

1. Variable convergence: The input elements are accumulated into a variable container, such as collection or StringBuilder;

List<integer> nums = lists.newarraylist (1,1,null,2,3,4,null,5,6,7,8,9,10);
       list<integer> numswithoutnull = Nums.stream (). filter (num-> num!= null).
               Collect (()-> new arraylist<integer> (),
                       (list, item)-> List.add (item),
                       (List1, List2)-> List1.addall (List2));
The above code is a list of integers of an element, filtering out all of the null, and then collecting the remaining elements into a new list. Take a closer look at the three parameters of the Collect method, which are lambda-form functions (* The above code can be simplified using method references and left to the reader to think for themselves *).

The first function generates a new ArrayList instance;
The second function accepts two parameters, the first one being the ArrayList object that was previously generated, and two being the element contained in the stream, which is to add the elements in the stream to the ArrayList object. The second function is called repeatedly until the elements of the original stream are consumed;
The third function is to accept two parameters, both of which are ArrayList types, and the function body is to add the second ArrayList all to the first;

But the Collect method call above is also a bit too complicated, it doesn't matter. Let's take a look at another version of the Collect method, which relies on the override

<r, a> R collect (collector< Super T, A, r> Collector);

JAVA8 also provided us with the Collector tool class –[collectors] which has already defined some static factory methods, such as: Collectors.tocollection () collection to collection, Collectors.tolist () is collected into the list and Collectors.toset () is collected into set. There are a lot of such static methods, here will not be introduced, we can go directly to see Javadoc. Here's a look at simplifying your code with collectors:

list<integer> numswithoutnull = Nums.stream (). filter (num-> num!= null).
                Collect (Collectors.tolist ());


2. Other convergence: Removing the rest of the variable convergence is not usually done by repeatedly modifying a mutable object, but by taking the previous aggregation result as the next entry, and so on. such as Reduce,count,allmatch;
Reduce method:The reduce method is very generic and can be implemented using the Count,sum described later. The reduce method has three override methods, this article describes two most commonly used, and the last one is left to the reader to learn. First look at the first form of the reduce method, whose method is defined as follows:

optional<t> reduce (binaryoperator<t> accumulator);
Accepts a binaryoperator type of argument that we can use in lambda expressions when used.
list<integer> ints = lists.newarraylist (1,2,3,4,5,6,7,8,9,10);
System.out.println ("INTs sum is:" + ints.stream (). Reduce (sum, item)-> sum + Item).
You can see that the reduce method accepts a function This function has two parameters, the first parameter is the return value (also known as the intermediate result) of the last function execution, and the second parameter is the element in the stream, which adds the two values together and assigns the first argument to the next execution of the function. NOTE: * * The first value of the first parameter is the first element of the stream, and the second is the second element of the stream. The return value type of this method is optional, a possible way to prevent NPE from appearing in the Java8, which is described in more detail here, which is simply considered a container, which may contain 0 or 1 objects.
The reduce method also has a very common variant:

t reduce (t identity, binaryoperator<t> Accumulator);
This definition is basically consistent and different: it allows the user to provide a cyclic calculation of the initial value, if the stream is empty, the value is returned directly. And this method does not return optional because it does not have null values. Here is a direct example, no longer explained.
list<integer> ints = lists.newarraylist (1,2,3,4,5,6,7,8,9,10);
System.out.println ("INTs sum is:" + ints.stream (). Reduce (0, (sum, item)-> sum + item);

Count Method:Gets the number of elements in the stream. Relatively simple, here is a direct example, do not explain.

list<integer> ints = lists.newarraylist (1,2,3,4,5,6,7,8,9,10);
System.out.println ("INTs sum is:" + ints.stream (). Count ());

– Search for related
Allmatch:is not all elements in the stream satisfy the given matching criteria
AnyMatch: Is there any element in the stream that satisfies the matching criteria
FindFirst:Returns the first element in the stream, and returns an empty optional if the stream is empty
Nonematch: Is not all elements in the stream do not meet the given matching criteria
Max and min:Returns the maximum | minimum value in the stream by using the given comparer (Operator)
Here's an example of Allmatch and Max, and the rest of the method is for the reader to practice.

list<integer> ints = lists.newarraylist (1,2,3,4,5,6,7,8,9,10);
System.out.println (Ints.stream (). Allmatch (item-> Item <));
Ints.stream (). Max ((O1, O2)-> O1.compareto (O2)). Ifpresent (System.out::p rintln);


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.