Java Stream Action Instance-filter, map, find matching __java

Source: Internet
Author: User

preparatory work

Build a test class that initializes a data source by testing the class, as follows.

public class Testobject {
    private String name;
    Private String sex;
    private int age;
    private String Email;
    Private Boolean ismng;

    Public Testobject () {
    } public

    testobject (String name,string sex,int age,string email,boolean ismng) {
        This.name=name;
        This.sex=sex;
        This.age=age;
        This.email=email;
        this.ismng=ismng;
    }
... get, set method does not post, much trouble
}

To define an initialization data source in a test class

public class Streamoperation {
    static list<testobject> List = Arrays.aslist (
            new Testobject ("Ron", "M", 10 , "ron.zheng@tfschange.com", false),
            new Testobject ("KDS", "W", Ten, "kds@qq.com", false),
            new Testobject (" Boduo ", W", M, "boduo@163.com", false),
            new Testobject ("Cangjin", "W", Ten, "cangjin@gmail.com", false),
            new Testobject ("Xiaoze", "W", "xiaoze@hotmail.com", true),
            new Testobject ("James", "M", 10, " Leblonjames@hotmail.com ", True),
            new Testobject (" Allen "," M ", X," allen.lei@tfschange.com ", true),
            new Testobject ("Smith", "M", Ten, "jr.smith@cel.com", true),
            new Testobject ("Wade", "M",, "dw.wade@cel.com", true),
   new Testobject ("Wade", "M",, "dw.wade@cel.com", false)
            );
//... ... Stream Operation
}

Filtering with predicates

The streams interface supports the filter method, which takes a predicate (a Boolean-returning function) as an argument and returns a stream that includes all elements that conform to the predicate. For example, we need to filter isleader for ture data and print the name can be processed as follows.

/**
     * @Comment get leader
     * @Author Ron
     * @Date November 24, 2017 afternoon 2:01:16
     * @return * * Public
    Static List<testobject> Getleader () {return
        List.stream (). Filter (Testobject::isleader). Collect ( Collectors.tolist ());
    }

    public static void Main (string[] args) {
        list<testobject> leaders = Getleader ();
        Leaders.stream (). ForEach (Leader->system.out.println (Leader.getname ()));
    

filter for different elements

The stream also supports a method called DISTINCT, which returns a stream of different elements (based on the hashcode and equals methods of the elements generated by the stream). For example, the following code filters out all the even numbers in the list and ensures that there are no duplicates.

public static void Main (string[] args) {
        list<integer> numbers = arrays.aslist (1, 2, 1, 3, 3, 2, 4);
        Numbers.stream (). Filter (i-> i% 2 = 0). Distinct (). ForEach (System.out::p rintln);
    

truncated short Stream

The stream supports the limit (n) method, which returns a stream that does not exceed a given length. The desired length is passed to the limit as a parameter. If the stream is ordered, the top n elements are returned at most. For example, select the first 5 objects sex m and print their names to follow the following code.

List.stream (). Filter (U->u.getsex (). Equals ("M")). Limit (5). ForEach (U->system.out.println (U.getname ()));

If we need to select the first 5 sex m objects and print their names after sorting by name, we can follow the following code.

List.stream ().
        Filter (U->u.getsex (). Equals ("M"))
        . Limit (5)
        . Sorted (Comparator.comparing ( testobject::getname))
        . ForEach (U->system.out.println (U.getname ()));

Skip Element

The stream also supports the Skip (n) method, which returns a stream that throws out the first n elements. If the element in the stream is less than N, an empty stream is returned. Please note that limit (n) and Skip (n) are complementary. For example, the following code skips the first element that is filtered out and prints the name.

List.stream ().
        Filter (U->u.getsex (). Equals ("M"))
        . Sorted (comparator.comparing (Testobject::getname))
        . Skip (1)
        . ForEach (U->system.out.println (U.getname ()));

each element of the convection applies a function

Stream supports the map method, which takes a function as an argument. This function is applied to each element and maps it to a new element (using the word map because it is similar to a transformation, but the subtle difference is that it is "create a new version" rather than "modify"). For example, the following code passes the method reference Testobject::getname to the map method to extract the name of the user in the stream and print:

List.stream ()
. Map (testobject::getname)
. Collect (Collectors.tolist ())
. ForEach (system.out::p rintln );

Because the GetName method returns a String, the type of the stream that the map method outputs is the stream string>.

Let's take another example, we passed the method reference Testobject::getname to the map method to extract the name of the user in the stream and then print the length of the user's name. You can solve this problem by passing a method reference string::length to the map as follows:

List.stream ().
        map (testobject::getname).
        map (string::length).
        Collect (Collectors.tolist ()
        ). ForEach (System.out::p rintln);

checks whether a predicate matches at least one element

The AnyMatch method can answer "whether an element in the stream can match a given predicate". For example, you can use it to see if there are any objects named Ron in the list of users to choose from:

if (List.stream (). AnyMatch (U->u.getname (). Equals ("Ron")) {
        System.out.println ("Ron has arrived");
    }

The AnyMatch method returns a Boolean and therefore is a terminal operation.

check whether the predicate matches all elements

The Allmatch method works like AnyMatch, but it looks at whether the elements in the stream can match the given predicate. For example, you can use it to see if the user is more than 10 years old.

if (List.stream (). Allmatch (U->u.getage () >=10)) {
        System.out.println ("Great, all greater than 10 years old");
    } else{
        System.out.println ("not yet developed");
    }

The opposite of Allmatch is nonematch. It ensures that no elements in the stream match the given predicate. For example, you can rewrite the previous example with Nonematch:

if (List.stream (). Nonematch (U->u.getage () <10)) {
        System.out.println ("Great, all greater than 10 years old");
    } else{
        System.out.println ("not yet developed");
    }

AnyMatch, Allmatch and nonematch all of these three operations are used in our so-called short-circuit, this is the familiar Java && and | | Operator short-circuit the version in the stream.

Optional Introduction

The Optional<t> Class (java.util.Optional) is a container class that represents whether a value exists or does not exist. Java 8 Library designers introduced Optional<t>, so that you do not have to return to the notoriously problematic null. There are several situations in optional that force you to explicitly check whether a value exists or if the value does not exist. Ispresent () returns True when optional contains a value, otherwise it returns false. The Ifpresent (Consumer block) executes the given blocks of code when the value exists. T get () returns a value when the value is present, otherwise a nosuchelement exception is thrown. T OrElse (t other) returns a value when the value is present, otherwise it returns a default value.

Find Elements

The Findany method returns any element in the current stream. It can be used in conjunction with other streaming operations.

For example, we need to show the check if there is a person named ' Ron ' and display its name to follow the following code.

List.stream ().
        Filter (U->u.getname (). Equals ("Ron"))
        . Findany ().
        Ifpresent (u-> System.out.println (U.getname ()));

The assembly line will be optimized in the background so that it simply goes through, and ends immediately when the result is found using a short-circuit.

find the first element

Some streams have a sequence of occurrences (encounter order) that specifies the logical order in which items appear in a stream (such as a stream generated by a list or a sorted column of data). For this flow, you may want to find the first element. There is a FindFirst method for this, and it works in a similar way to Findany.

For example, we need to find the first object Isleader as ture and print its name, and we can follow the following code.

List.stream ().
        Filter (U->u.isleader ())
        . FindFirst ().
        Ifpresent (U->system.out.println ( U.getname ()));

when to use FindFirst and Findany

You may wonder why there are FindFirst and findany at the same time. The answer is parallel. Find the first element to limit it more in parallel. If you don't care what the returned element is, use findany because it has fewer restrictions when using parallel streams.

Reference: Java8 Combat

Related Article

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.