Java 8 Stream API details 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, and it is an enhancement to the functionality of the collection object, focusing 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 many languages that support functional programming, map () and reduce () are mostly built into the standard library of languages, but the stream API for Java 8 is generally quite complete and powerful enough to accomplish many 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. It also provides both serial and parallel modes for aggregation, and the concurrency pattern leverages the benefits of multi-core processors to split tasks and accelerate processing using fork/join parallel methods. Writing parallel code is often difficult and error-prone, but using the stream API makes it easy to write high-performance concurrent programs without having to write a single line of multithreaded code.
In the stream API, a stream basically represents a sequence of elements, and the stream API provides a rich array of manipulation functions to calculate these elements. In the past when we were developing business applications, it was common for many implementations to do this: 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 whole bunch of ugly sequential code.
If we use the Stream API to do the same thing, using lambda expressions and other functions for abstraction can make the code easier to understand and cleaner. With these abstractions, you can also do some optimizations, such as implementing parallelism.
Second, Stream API instance 1. Use Intstream to remove regular loops
For example, in the console output 0~9:
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, sort, and then export all the 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" };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 by 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));
Copyright NOTICE: This article for Bo Master Chszs original article, without Bo Master permission not reproduced.
Java 8 Stream API detailed