The Java 8 API adds a new abstraction called Stream Stream that lets you process data in a declarative manner.
Stream uses an intuitive way to query data from a database using SQL statements to provide a high-level abstraction of operations and expressions on Java collections.
The Stream API can greatly increase the productivity of Java programmers, allowing programmers to write efficient, clean and concise code.
This style treats the set of elements to be treated as a kind of stream. The stream is transmitted in the pipeline and can be processed on the nodes of the pipeline, such as filtering, sorting, aggregation, and so on.
The element stream is processed in an intermediate operation in the pipeline, and finally the result of the previous processing is obtained by a terminal operation.
+--------------------+ +------+ +------+ +---+ +-------+ | stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect| +--------------------+ +------+ +------+ +---+ +-------+
The above process is converted to Java code as:
List<Integer> transactionsIds = widgets.stream() .filter(b -> b.getColor() == RED) .sorted((x,y) -> x.getWeight() - y.getWeight()) .mapToInt(Widget::getWeight) .sum();
What is Stream?
Stream is an element queue from a data source and supports aggregation operations
- Elements are specific types of objects that form a queue. Streams in Java do not store elements, but they are calculated on demand.
- The source of the data source stream. It can be a collection, an array, an I/O channel, a generator, etc.
- Aggregate operations are similar to SQL statements, such as filter, map, reduce, find, match, sorted, and so on.
Unlike the previous Collection operation, the Stream operation has two basic features:
- Pipelining : Intermediate operations will return the stream object itself. This way multiple operations can be cascaded into one pipeline, just like a fluent style. Doing so can optimize operations, such as laziness and short-circuiting.
- Internal Iteration : Previously, the collection traversal was through the Iterator or For-Each way. Iteratively iterating outside the collection. This is called external iteration. Stream provides internal iterative methods that are implemented through the Visitor mode.
Generate flow
In Java 8, the collection interface has two methods to generate the stream:
- Stream () − Creates a serial stream for the collection.
- parallelStream() − Creates a parallel stream for the collection.
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
forEach
Stream provides a new method 'forEach' to iterate over each data in the stream. The following code fragment uses forEach to output 10 random numbers:
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
Map
The map method is used to map each element to the corresponding result. The following code fragment uses map to output the square of the element:
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// Get the corresponding squares
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
Filter
The filter method is used to filter out elements by the set conditions. The following code snippet uses the filter method to filter out the empty string:
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// Get the number of empty strings
int count = strings.stream().filter(string -> string.isEmpty()).count();
Limit
The limit method is used to get the specified number of streams. The following code fragment uses the limit method to print out 10 pieces of data:
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
Sorted
The sorted method is used to sort the stream. The following code snippet uses the sorted method to sort the output of 10 random numbers:
Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);
Parallel program
parallelStream is an alternative to streaming parallel processing. In the following example we use parallelStream to output the number of empty strings:
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// Get the number of empty strings
int count = strings.parallelStream().filter(string -> string.isEmpty()).count();
We can easily switch between sequential operation and parallel switching.
Collectors
The Collectors class implements many reduction operations, such as converting streams to collections and aggregation elements. Collectors can be used to return lists or strings:
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
System.out.println("Filtering List: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("Merge string: " + mergedString);
statistics
In addition, some collectors that generate statistical results are also very useful. They are mainly used for int, double, long and other basic types, they can be used to produce statistical results similar to the following.
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = integers.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("The largest number in the list: " + stats.getMax());
System.out.println("The smallest number in the list: " + stats.getMin());
System.out.println("The sum of all numbers: " + stats.getSum());
System.out.println("average: " + stats.getAverage());
Stream full instance
Put the following code in the Java8Tester.java file:
Java8Tester.java file
import java.util.ArrayList;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.Map;
public class Java8Tester {
public static void main(String args[]){
System.out.println("Using Java 7: ");
// evaluate empty string
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
System.out.println("List: " +strings);
long count = getCountEmptyStringUsingJava7(strings);
System.out.println("number of null characters: " + count);
count = getCountLength3UsingJava7(strings);
System.out.println("string of length 3 is: " + count);
// Delete empty string
List<String> filtered = deleteEmptyStringsUsingJava7(strings);
System.out.println("Filtered list: " + filtered);
// Delete empty strings and combine them using commas
String mergedString = getMergedStringUsingJava7(strings,", ");
System.out.println("merged string: " + mergedString);
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// Get the square of the list element
List<Integer> squaresList = getSquares(numbers);
System.out.println("squares list: " + squaresList);
List<Integer> integers = Arrays.asList(1,2,13,4,15,6,17,8,19);
System.out.println("List: " +integers);
System.out.println("maximum number in the lists : " + getMax(integers));
System.out.println("minimum number in the list : " + getMin(integers));
System.out.println("Get Sum : " + getSum(integers));
System.out.println("Average : " + getAverage(integers));
System.out.println("random number: ");
// Output 10 Random numbers
Random random = new Random();
for(int i=0; i < 10; i++){
System.out.println(random.nextInt());
}
System.out.println("Using Java 8: ");
System.out.println("List: " +strings);
count = strings.stream().filter(string->string.isEmpty()).count();
System.out.println("The number of empty strings are: " + count);
count = strings.stream().filter(string -> string.length() == 3).count();
System.out.println("string of length 3 is: " + count);
filtered = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.toList());
System.out.println("Filtered list: " + filtered);
mergedString = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("Merged string: " + mergedString);
squaresList = numbers.stream().map( i ->i*i).distinct().collect(Collectors.toList());
System.out.println("Squares List: " + squaresList);
System.out.println("List: " +integers);
IntSummaryStatistics stats = integers.stream().mapToInt((x) ->x).summaryStatistics();
System.out.println("maximum number in the lists : " + stats.getMax());
System.out.println("minimum number in the list : " + stats.getMin());
System.out.println("Get Sum : " + stats.getSum());
System.out.println("Average : " + stats.getAverage());
System.out.println("random number: ");
random.ints().limit(10).sorted().forEach(System.out::println);
// parallel processing
count = strings.parallelStream().filter(string -> string.isEmpty()).count();
System.out.println("number of empty strings: " + count);
}
private static int getCountEmptyStringUsingJava7(List<String> strings){
int count = 0;
for(String string: strings){
if(string.isEmpty()){
count++;
}
}
return count;
}
private static int getCountLength3UsingJava7(List<String> strings){
int count = 0;
for(String string: strings){
if(string.length() == 3){
count++;
}
}
return count;
}
private static List<String> deleteEmptyStringsUsingJava7(List<String> strings){
List<String> filteredList = new ArrayList<String>();
for(String string: strings){
if(!string.isEmpty()){
filteredList.add(string);
}
}
return filteredList;
}
private static String getMergedStringUsingJava7(List<String> strings, String separator){
StringBuilder stringBuilder = new StringBuilder();
for(String string: strings){
if(!string.isEmpty()){
stringBuilder.append(string);
stringBuilder.append(separator);
}
}
String mergedString = stringBuilder.toString();
return mergedString.substring(0, mergedString.length()-2);
}
private static List<Integer> getSquares(List<Integer> numbers){
List<Integer> squaresList = new ArrayList<Integer>();
for(Integer number: numbers){
Integer square = new Integer(number.intValue() * number.intValue());
if(!squaresList.contains(square)){
squaresList.add(square);
}
}
return squaresList;
}
private static int getMax(List<Integer> numbers){
int max = numbers.get(0);
for(int i=1;i < numbers.size();i++){
Integer number = numbers.get(i);
if(number.intValue() > max){
max = number.intValue();
}
}
return max;
}
private static int getMin(List<Integer> numbers){
int min = numbers.get(0);
for(int i=1;i < numbers.size();i++){
Integer number = numbers.get(i);
if(number.intValue() < min){
min = number.intValue();
}
}
return min;
}
private static int getSum(List numbers){
int sum = (int)(numbers.get(0));
for(int i=1;i < numbers.size();i++){
sum += (int)numbers.get(i);
}
return sum;
}
private static int getAverage(List<Integer> numbers){
return getSum(numbers) / numbers.size();
}
}
Execute the above script, the output is:
Using Java 7: List: [abc, , bc, efg, abcd, , jkl] number of null characters: 2 string of length 3 is: 3 Filtered list: [abc, bc, efg, abcd, jkl] merged string: abc, bc, efg, abcd, jkl squares list: [9, 4, 49, 25] List: [1, 2, 13, 4, 15, 6, 17, 8, 19] maximum number in the lists : 19 minimum number in the list : 1 Get Sum : 85 Average : 9 random number: -21008070 152579057 -2140275464 995131737 943707503 -773217689 1486154966 -1261421423 -1515491670 -55443530 Using Java 8: List: [abc, , bc, efg, abcd, , jkl] The number of empty strings are: 2 string of length 3 is: 3 Filtered list: [abc, bc, efg, abcd, jkl] Merged string: abc, bc, efg, abcd, jkl Squares List: [9, 4, 49, 25] List: [1, 2, 13, 4, 15, 6, 17, 8, 19] maximum number in the lists : 19 minimum number in the list : 1 Get Sum : 85 Average : 9.444444444444445 random number: -1642312005 -1471648151 -1240705703 -745323641 166392553 284703424 587292496 1652665060 1665633275 2113342259 number of empty strings: 2
Comments
Post a Comment