JAVA 8 New Feature Stream First Experience

Keywords: Java SQL

What is Stream?

Stream is an element queue from a data source and supports aggregation operations

  • The <strong="> element queue is a specific type of object, forming a queue. Stream in Java does not store elements, but computes on demand.
  • Sources of data sources and streams. They can be collections, arrays, I/O channel s, generator s, etc.
  • Aggregation operations like SQL statements, such as filter, map, reduce, find, match, sort, etc.

Unlike previous Collection operations, Stream operations have two basic features:

  • Pipelining: Intermediate operations return the flow object itself. This allows multiple operations to be connected in series to form a pipeline, like a fluent style. This can optimize operations such as laziness and short-circuiting.
  • Internal iteration: In the past, iterations on collections were performed explicitly outside collections through Iterator or For-Each, which is called external iteration. Stream provides an internal iteration approach, implemented through Visitor mode.

Title:

There is a collection, which stores strings such as "Xiaowang, 98", "Xiaoli, 95", "Xiaochen, 87". It requires printing out numbers with more than 90 points in all grades.

Conventional writing

 1     public static void main(String[] args) {
 2         ArrayList<String> arrayList=new ArrayList<String>();
 3         arrayList.add("Xiao Wang,98");
 4         arrayList.add("petty thief,95");
 5         arrayList.add("Xiao Chen,87");
 6         for (int i = 0; i < arrayList.size(); i++) {
 7             String record=arrayList.get(i);
 8             String score=record.split(",")[1];
 9             int num =Integer.parseInt(score);
10             if (num>90) {
11                 System.out.println(num);
12             }
13         }
14     }

Stream mode

1     public static void main(String[] args) {
2         ArrayList<String> arrayList=new ArrayList<String>();
3         arrayList.add("Xiao Wang,98");
4         arrayList.add("petty thief,95");
5         arrayList.add("Xiao Chen,87");
6         arrayList.stream().map(s->s.split(",")[1]).map(Integer::parseInt)
7         .filter(n -> n > 90).forEach(System.out::println);
8     }

Detailed introduction of Stream method

Generating stream

  • stream() Creates a serial stream for a collection.

  • parallelStream() Creates parallel flows for collections.

Serial stream

1     public static void main(String[] args) {
2         //Generate streams and filter out collections that are not empty strings
3         List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
4         List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
5         for (int i = 0; i < filtered.size(); i++) {
6             System.out.println(filtered.get(i));
7         }
8     }

Parallel flow

1     public static void main(String[] args) {        
2         List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
3         // Gets the number of empty strings
4         long count = strings.parallelStream().filter(string -> string.isEmpty()).count();
5         System.out.println(count);
6     }

2. forEvery

  • Stream provides a new method, 'forEach', to iterate over each data in the stream.
 1     public static void main(String[] args) {
 2         //Use forEach Traversing the numbers in a printed set
 3         ArrayList<Integer> arrayList=new ArrayList<Integer>();
 4         arrayList.add(1);
 5         arrayList.add(2);
 6         arrayList.add(3);
 7         arrayList.add(4);
 8         arrayList.add(5);
 9         arrayList.add(6);
10         arrayList.stream().forEach(System.out::println);        
11     }    

Three, map

  • The map method is used to map each element to its corresponding result. The following code snippet uses map to output the corresponding square of the element:
1     public static void main(String[] args) {
2         //Use map Squares corresponding to output elements
3         List<Integer> numbers = Arrays.asList(1,2,3,4,5,6);
4         numbers.stream().map(i->i*i).forEach(System.out::println);
5     }

Four, filter

  • The filter method is used to filter out elements through the set conditions.
1     public static void main(String[] args) {
2         //Use filter Method to filter the number of empty strings
3         List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
4         long count = strings.stream().filter(string -> string.isEmpty()).count();
5         System.out.println(count);
6     }

Five, limit

  • The limit method is used to get a specified number of streams.
 1     public static void main(String[] args) {
 2         //Use limit Method Print out 3 pieces of data:
 3         ArrayList<Integer> arrayList = new ArrayList<Integer>();
 4         arrayList.add(1);
 5         arrayList.add(2);
 6         arrayList.add(3);
 7         arrayList.add(4);
 8         arrayList.add(5);
 9         arrayList.add(6);
10         arrayList.stream().limit(3).forEach(System.out::println);
11     }

Six, sorted

  • The sorted method is used to sort convections. The following code snippets use the sorted method to sort the 10 random numbers output:
 1     public static void main(String[] args) {        
 2         //Use sorted Sort the elements in the method set:
 3         ArrayList<Integer> arrayList = new ArrayList<Integer>();
 4         arrayList.add(1);
 5         arrayList.add(22);
 6         arrayList.add(13);
 7         arrayList.add(45);
 8         arrayList.add(50);
 9         arrayList.add(6);
10         arrayList.stream().sorted().forEach(System.out::println);
11     }

Collectors

  • The Collectors class implements many reduction operations, such as transforming streams into collection and aggregation elements. Collectors can be used to return lists or strings:
1     public static void main(String[] args) {
2         List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
3         List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
4 
5         System.out.println("Filter list: " + filtered);
6         String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
7         System.out.println("Merge strings: " + mergedString);
8     }

Eight, statistics

  • Some collectors that produce statistical results are also very useful. They are mainly used for basic types such as int, double, long, etc. They can be used to produce statistical results similar to the following.
 1     public static void main(String[] args) {        
 2         List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
 3          
 4         IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();
 5          
 6         System.out.println("The largest number in the list : " + stats.getMax());
 7         System.out.println("The smallest number in the list : " + stats.getMin());
 8         System.out.println("The sum of all numbers : " + stats.getSum());
 9         System.out.println("Average : " + stats.getAverage());
10     }

If it's helpful to you, thank you.

Posted by ERuiz on Tue, 08 Oct 2019 10:46:55 -0700