JAVA 8 Streams and javastreams

Source: Internet
Author: User
Tags stream api

JAVA 8 Streams and javastreams
What is Stream?

First, do not be fooled by its name. Here, Stream is different from InputStream and OutputStream in java I/O. Stream in Java 8 is actually the concept of Monad in functional programming. Monad is still abstract and hard to understand. You can refer to this article. I personally think it is better to understand it, simply put, Monad is a design pattern that refers to splitting an operation process into multiple interconnected steps through functions, which is a bit chained.

The following is an example of Stream.

Import java. util. arrays; import java. util. list; public class Snippet {public static void main (String [] args) {List <String> myList = Arrays. asList ("a1", "a2", "b1", "c2", "c1"); myList. stream (). filter (s-> s. startsWith ("c") // filter data that starts with a c letter. map (String: toUpperCase) // converts the String to uppercase. sorted () // sort. forEach (System. out: println); // Print Output }}
Benefits of using Stream
  • The JAVA Collection object function is enhanced to facilitate various operations on the Collection (filtering, maximization, minimum, statistics, etc );
  • It is more efficient. It provides two serial and parallel modes. The parallel mode utilizes the fork/join framework technology in Java to fully utilize multi-core processors and improve program concurrency;
Stream features
  • Not a Data Structure
  • Designed for lambda expressions
  • Index access is not supported.
  • It is easy to output as an array or set.
  • Support for inert access
  • Parallel Computing
How to obtain Stream objects from Collection and array
  • Collection. stream ()
  • Collection. parallelStream ()
  • Arrays. stream (T array) or Stream. ()
From BufferedReader
  • Java. io. BufferedReader. lines ()
Static Factory
  • Java. util. stream. IntStream. range ()
  • Java. nio. file. Files. walk ()
Create by yourself
  • Java. util. Spliterator
Others
  • Random. ints ()
  • BitSet. stream ()
  • Pattern. splitAsStream (java. lang. CharSequence)
  • JarFile. stream ()
  • ...
Stream Operation Type

Stream has two types of operations: Intermediate and Terminal.

Intermediate (Intermediate Operation)

Stream can perform multiple Intermediate operations. For example, in the example above, filter, map, and sorted are all Intermediate operations. Note that this operation is inert, when this method is called, Stream traversal is not actually started.

Terminal)

A Stream has only one Terminal operation. For example, in the example above, forEach is the Terminal operation, and the Terminal operation is the last operation of Stream. At this time, Stream traversal starts.

Stream creation using the example Stream

Use Stream.

import java.util.stream.Stream;public class StreamBuilders{    public static void main(String[] args)    {        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9);        stream.forEach(p -> System.out.println(p));    }}

Use Arrays. stream

import java.util.Arrays;import java.util.stream.Stream;public class StreamBuilders{    public static void main(String[] args)    {        Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9});        stream.forEach(p -> System.out.println(p));    }}

Use Collection. stream () or Collection. parallelStream ()

import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Stream;public class StreamBuilders{    public static void main(String[] args)    {        List<Integer> list =             new ArrayList<Integer>(Arrays.asList(new Integer[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }));                Stream<Integer> stream = list.stream();    //or list.parallelStream();        stream.forEach(p -> System.out.println(p));    }}

Use IntStream. range

import java.util.stream.IntStream;public class StreamBuilders{    public static void main(String[] args)    {        IntStream stream = IntStream.range(1, 9);        stream.forEach(p -> System.out.println(p));    }}

Use Random. ints ()

import java.util.Random;import java.util.stream.IntStream;public class StreamBuilders{    public static void main(String[] args)    {        IntStream stream = new Random().ints(1, 10);        stream.forEach(p -> System.out.println(p));    }}

Use Stream. generate ()

import java.util.concurrent.TimeUnit;import java.util.stream.Stream;public class StreamBuilders{    static int i = 0;    public static void main(String[] args)    {        Stream<Integer> stream = Stream.generate(() -> {            try            {                TimeUnit.SECONDS.sleep(1);            }            catch (InterruptedException e)            {                e.printStackTrace();            }            return i++;        });        stream.forEach(p -> System.out.println(p));    }}

There are many others, which are not listed here.

Stream type to set/array type

Use stream. collect (Collectors. toList ())

import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;public class StreamBuilders{    public static void main(String[] args)    {        List<Integer> list =             new ArrayList<Integer>(Arrays.asList(new Integer[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }));                Stream<Integer> stream = list.stream();                List<Integer> evenNumbersList = stream.filter(i -> i % 2 == 0).collect(Collectors.toList());                System.out.print(evenNumbersList);    }}

Use stream. toArray (EntryType []: new)

import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Stream;public class StreamBuilders{    public static void main(String[] args)    {        List<Integer> list =             new ArrayList<Integer>(Arrays.asList(new Integer[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }));                Stream<Integer> stream = list.stream();                Integer[] evenNumbersArr = stream.filter(i -> i % 2 == 0).toArray(Integer[]::new);                System.out.print(Arrays.asList(evenNumbersArr));    }}

Others are converted to set and map, which are not listed one by one.

Core Stream Operation Method

 Intermediate (Intermediate operation), which lists only the common

Filter method, filter elements

import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Stream;public class StreamBuilders{    public static void main(String[] args)    {        List<String> list = new ArrayList<String>(Arrays.asList(new String[]{                     "Amitabh", "Shekhar", "Aman", "Rahul",                     "Shahrukh", "Salman", "Yana", "Lokesh"}));                Stream<String> stream = list.stream();                stream.filter((s) -> s.startsWith("A")).forEach(System.out::println);    }}

Map Method, modify elements

import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Stream;public class StreamBuilders{    public static void main(String[] args)    {        List<String> list = new ArrayList<String>(Arrays.asList(new String[]{                     "Amitabh", "Shekhar", "Aman", "Rahul",                     "Shahrukh", "Salman", "Yana", "Lokesh"}));                Stream<String> stream = list.stream();                stream.filter((s) -> s.startsWith("A")).map(String::toUpperCase).forEach(System.out::println);    }}

Sorted method, sorting, You can input the custom sorting interface Comparator,

import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Stream;public class StreamBuilders{    public static void main(String[] args)    {        List<String> list = new ArrayList<String>(Arrays.asList(new String[]{                     "Amitabh", "Shekhar", "Aman", "Rahul",                     "Shahrukh", "Salman", "Yana", "Lokesh"}));                Stream<String> stream = list.stream();                stream.sorted().map(String::toUpperCase).forEach(System.out::println);    }}

Terminal)Here, only a few of the common

The example here is similar to the previous one, so we will not write all the code and list the important parts.

ForEach method, iteration element, and perform related operations

       stream.sorted().map(String::toUpperCase).forEach(System.out::println);

Collect method to obtain the set from Stream

        List<String> memNamesInUppercase = stream.sorted().map(String::toUpperCase).collect(Collectors.toList());        System.out.print(memNamesInUppercase);

Match Method to Determine whether the elements in the Stream comply with the specified rules

        boolean matchedResult = list.stream().anyMatch((s) -> s.startsWith("A"));        System.out.println(matchedResult);        matchedResult = list.stream().allMatch((s) -> s.startsWith("A"));        System.out.println(matchedResult);        matchedResult = list.stream().noneMatch((s) -> s.startsWith("A"));        System.out.println(matchedResult);

Count method, count

        long totalMatched = list.stream().filter((s) -> s.startsWith("A")).count();        System.out.println(totalMatched);

Reduce method, element combination operation, commonly used in String concatenation, value sum, min, max, average

Import java. util. arrayList; import java. util. arrays; import java. util. list; import java. util. optional; public class StreamBuilders {public static void main (String [] args) {List <String> list = new ArrayList <String> (Arrays. asList (new String [] {"Amitabh", "Shekhar", "Aman", "Rahul", "Shahrukh", "Salman", "Yana ", "Lokesh"}); Optional <String> balanced CED = list. stream (). reduce (s1, s2)-> s1 + "#" + s2); CED. ifPresent (System. out: println); // print the result: Amitabh # Shekhar # Aman # Rahul # Shahrukh # Salman # Yana # Lokesh }}
Stream short-circuit operation

The so-called short-circuit operation. It means that if the requirements are met, the following operations will not be continued, similar to & and | operations,

In Stream, similar methods include anyMatch () and findFirst,

AnyMatch () returns a Boolean value. If a matching element is found, the next element traversal is stopped;

        boolean matched = list.stream().anyMatch((s) -> s.startsWith("A"));        System.out.println(matched);        // Output: true

FindFirst (): returns the element. Similarly, only the first element is returned and not all elements are traversed;

        String firstMatchedName = list.stream().filter((s) -> s.startsWith("L")).findFirst().get();        System.out.println(firstMatchedName);        // Output: Lokesh
Concurrent parallelStream

Java 7 introduces the Fork/Join parallel computing framework, allowing us to split tasks and accelerate the processing in parallel. Generally, writing parallel code is difficult and error-prone, but using Stream API can easily write high-performance concurrent programs without writing a line of multi-thread code.

Example:

import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Stream;public class StreamBuilders{    public static void main(String[] args)    {        List<Integer> list =            new ArrayList<Integer>(Arrays.asList(new Integer[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }));                // Here creating a parallel stream        Stream<Integer> stream = list.parallelStream();        Integer[] evenNumbersArr = stream.filter(i -> i % 2 == 0).toArray(Integer[]::new);        System.out.print(Arrays.asList(evenNumbersArr));    }}
Comparison between Stream and Stream

The following example shows how to use Stream or not use Stream to count the number of strings with a length of 3.

Import java. util. arrays; import java. util. list; public class Java8Tester {public static void main (String args []) {List <String> strings = Arrays. asList ("abc", "111", "bc", "efg", "12584", "", "1254"); // use Java 7, count the number of strings with a length of 3 long count = 0; for (String string: strings) {if (string. length () = 3) {count ++;} System. out. println ("using java7: Strings of length 3:" + count); // use a stream of Java 8 to count the number of strings with a length of 3. count = Strings. stream (). filter (string-> string. length () = 3 ). count (); System. out. println ("using java8: Strings of length 3:" + count );}}
References

Http://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/

Http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/

Https://www.tutorialspoint.com/java8/java8_streams.htm

Http://howtodoinjava.com/core-java/collections/java-8-tutorial-streams-by-examples/

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.