Java 8 Stream API specific explanation

Source: Internet
Author: User
Tags stream api java 8 stream

Java 8 Stream API specific explanation one, stream API introduction

Java 8 introduces a new stream API, which is completely different from the InputStream and outputstream in Java I/O packages, unlike the Stax stream for XML parsing, and unlike Amazon Kinesis stream for real-time processing of big data. The Stream API is more like a collection class with iterable, but behaves differently from the collection class, which is an enhancement to the functionality of the collection object. Focus on a variety of very convenient, efficient aggregation operations or bulk data operations on collection objects.

The Stream API is introduced to compensate for the flaws in Java functional programming. For very many languages that support functional programming. Map (), reduce () are basically built into the standard library of languages. Just, Java 8 's stream API is still very intact and powerful enough to complete a lot of complex functions with very little code.

The stream API of Java 8 takes full advantage of the nature of lambda expressions, greatly improving programming efficiency and program readability.

At the same time it provides both serial and parallel modes for aggregation, and the concurrency pattern takes advantage of the multi-core processor to split tasks and speed up processing using fork/join parallel methods.

Writing parallel code is often difficult and easy error. But using the Stream API does not require writing a single line of multithreaded code. It is very convenient to write high-performance concurrent programs.

In the Stream API. A stream basically represents an element sequence, and the stream API provides a rich array of manipulation functions to calculate these elements. When we were developing business applications, it was usually a very large implementation of operations: we used loops to iterate over the collection, to implement various operations on the elements in the collection, to define various variables to achieve the purpose, so that we got a bunch of ugly sequential code.

Let's say we use the Stream API to do the same thing, use lambda expressions and other functions to abstract, making the code easier to understand and cleaner. With these abstractions, you can also do some optimizations, such as parallel implementations.

Second, Stream API instance 1. Use Intstream to remove regular loops

For example, in the console output 0~9 sample:
Attention needs import Java.util.stream.IntStream;

IntStream.range(0, 10).forEach(value -> System.out.println(value));
2. Calculating the number of elements in a list

Note You need to

import java.util.List;import java.util.stream.Collectors;import java.util.stream.IntStream;List<Integer> list = IntStream.range(1, 100).boxed().collect(Collectors.toList());System.out.println(list.stream().count());
3. Calculating the average number of elements in a list
Double avarage = list.stream().collect(Collectors.averagingInt(item -> item));
4. Statistics on List elements
List<Integer> list = IntStream.range(1, 100).boxed().collect(Collectors.toList());IntSummaryStatistics iss = list.stream().collect(Collectors.summarizingInt(value -> value));System.out.println(iss);

?
Output Result:

IntSummaryStatistics{count=99, sum=4950, min=1, average=50.000000, max=99}
5. Create a map based on list
List<Integer> list = IntStream.range(1, 100).boxed().collect(Collectors.toList());Map<Integer, Integer> map = list.stream().collect(Collectors.toMap(p -> p, q->q*3));System.out.println(map);

Output Result:

{1=3, 2=6, 3=9, 4=12, 5=15, 6=18, 7=21, 8=24, 9=27, 10=30, 11=33, 12=36, 13=39, 14=42, 15=45, 16=48, 17=51, 18=54, 19=57, 20=60, 21=63, 22=66, 23=69, 24=72, 25=75, 26=78, 27=81, 28=84, 29=87, 30=90, 31=93, 32=96, 33=99, 34=102, 35=105, 36=108, 37=111, 38=114, 39=117, 40=120, 41=123, 42=126, 43=129, 44=132, 45=135, 46=138, 47=141, 48=144, 49=147, 50=150, 51=153, 52=156, 53=159, 54=162, 55=165, 56=168, 57=171, 58=174, 59=177, 60=180, 61=183, 62=186, 63=189, 64=192, 65=195, 66=198, 67=201, 68=204, 69=207, 70=210, 71=213, 72=216, 73=219, 74=222, 75=225, 76=228, 77=231, 78=234, 79=237, 80=240, 81=243, 82=246, 83=249, 84=252, 85=255, 86=258, 87=261, 88=264, 89=267, 90=270, 91=273, 92=276, 93=279, 94=282, 95=285, 96=288, 97=291, 98=294, 99=297}
6. Find the maximum number of list elements
List<Integer> list = new Random().ints(-100,100).limit(250).boxed().collect(Collectors.toList());Optional<Integer> max = list.stream().reduce(Math::max);max.ifPresent(value -> System.out.println(value));
7. Find names that begin with the letter "C" from a list of names
?String[] names = { "Fred Edwards", "Anna Cox", "Deborah Patterson", "Ruth Torres", "Shawn Powell",                "Rose Thompson", "Rachel Barnes", "Eugene Ramirez", "Earl Flores", "Janice Reed", "Sarah Miller",                "Patricia Kelly", "Carl Hall", "Craig Wright", "Martha Phillips", "Thomas Howard", "Steve Martinez",                "Diana Bailey", "Kathleen Hughes", "Russell Anderson", "Theresa Perry" };List<String> ls = Arrays.asList(names).stream().filter(s -> s.startsWith("C")).collect(Collectors.toList());System.out.println(ls.toString());
8. Capitalize and sort all the names. Re-output
String[] names = { "Fred Edwards", "Anna Cox", "Deborah Patterson", "Ruth Torres", "Shawn Powell",                "Rose Thompson", "Rachel Barnes", "Eugene Ramirez", "Earl Flores", "Janice Reed", "Sarah Miller",                "Patricia Kelly", "Carl Hall", "Craig Wright", "Martha Phillips", "Thomas Howard", "Steve Martinez",                "Diana Bailey", "Kathleen Hughes", "Russell Anderson", "Theresa Perry" };Arrays.asList(names)         .stream()         .map(String::toUpperCase)         .sorted().forEach(System.out::println);
Third, more complex example 1. Create a Person class
public class Person {    private String name;    private int age;    public Person(String name, int age) {        super();        this.name = name;        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    @Override    public String toString() {        return name;    }}
2. Group the person according to age
Map<Integer, List<Person>> collect = persons.stream().collect(Collectors.groupingBy(Person::getAge));
3. Average age for all person
Double collect = persons.stream().collect(Collectors.averagingInt(Person::getAge));

Java 8 Stream API specific explanation

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.