As the embodiment of functional programming style, Stream stream really introduces this style into Java. We can perfectly understand the meaning in the code by directly reading the literal meaning, regardless of logic. Let's practice and learn together with the example to easily handle Stream stream!
Step 1: generate operation
There are several ways to generate a Stream, which is the cornerstone of subsequent operations.
Collection system collection
Generate a stream using the default method stream(), default stream()
Map system collection
Convert the Map into a Set set to indirectly generate a stream
array
Generate a Stream through the static method of(T... values) of the Stream interface
package com.csf.streamIO; import java.util.*; import java.util.stream.Stream; public class StreamDemo { // Common generation methods of Stream public static void main(String[] args) { // Liu generation mode under set system //list List<String> list = new ArrayList<String>(); Stream<String> listStream = list.stream(); //set HashSet<String> set = new HashSet<>(); Stream<String> setStream = set.stream(); // Set indirect generation flow in map system Map<String, Integer> hashMap = new HashMap<>(); Stream<String> key = hashMap.keySet().stream(); Stream<Integer> valueStream = hashMap.values().stream(); Stream<Map.Entry<String, Integer>> setS = hashMap.entrySet().stream(); // The array generates a stream through the of method String[] str ={"z","x","e"}; Stream<String> str1 = Stream.of(str); // Direct way Stream<Integer> integerStream = Stream.of(10, 20, 30); Stream<String> z = Stream.of("z", "x", "e"); } }
Step 2: intermediate operation
concept
Intermediate operation means that after this method is executed, the Stream stream can still continue to perform other operations.
Common methods
Stream filter (predict): used to filter the data in the stream
Stream limit(long maxSize): returns the stream composed of elements in the stream and intercepts the data of the specified number of parameters before
Stream skip(long n): skip the data of the specified number of parameters and return the stream composed of the remaining elements of the stream
Static stream concat (stream a, stream b): merge two streams a and B into one stream
Stream distinct(): returns a stream composed of different elements of the stream (according to Object.equals(Object))
Stream sorted(): returns the stream composed of the elements of this stream, sorted according to the natural order
Stream sorted (Comparator comparator): returns the stream composed of the elements of the stream and sorts it according to the provided Comparator
Stream map(Function mapper): returns a stream consisting of the results of the elements to which the given function is applied
IntStream mapToInt(ToIntFunctionmapper): returns an IntStream containing the result of applying the given function to the element of this stream
package com.csf.streamIO; import java.util.ArrayList; import java.util.stream.Stream; public class StreamDemo01 { public static void main(String[] args) { ArrayList<String> strings = new ArrayList<>(); strings.add("Zhou Enlai"); strings.add("Zhou Yuer"); strings.add("Big Joe"); strings.add("Little Joe"); strings.add("around"); strings.add("Zhuge Liang"); strings.add("Guan Yu"); //filter strings.stream().filter(s -> s.startsWith("week")).forEach(System.out::println); System.out.println("----------"); strings.stream().filter(s -> s.length()==3).forEach(System.out::println); System.out.println("----------"); strings.stream().filter(s -> s.startsWith("week")).filter(s -> s.length()==3).forEach(System.out::println); limit:Take out the parameters of the corresponding data in order strings.stream().limit(2).forEach(System.out::println); // Skip: skip several elements and remove all subsequent elements strings.stream().skip(5).forEach(System.out::println); // Skip three elements to the next two System.out.println("====================="); strings.stream().skip(3).limit(2).forEach(System.out::println); // Concat: it has the same meaning as database concat to merge // Get the stream composed of the first four data in the list System.out.println("====================="); Stream<String> limit = strings.stream().limit(4); // Get the stream composed of three parameters in the list Stream<String> skip = strings.stream().skip(3); // Merge operation // Stream.concat(limit,skip).forEach(System.out::println); // distinct de duplication: de duplication the duplicate parameters in the above example System.out.println("====================="); Stream.concat(limit,skip).distinct().forEach(System.out::println); // sorted sort ArrayList<String> list = new ArrayList<>(); list.add("asdf"); list.add("view"); list.add("world"); list.add("zezeze"); list.add("january"); list.add("yald"); list.add("ko"); // Print the data in alphabetical order on the console System.out.println("====================="); System.out.println("====================="); list.stream().sorted().forEach(System.out::println); // Sort output by string length System.out.println("====================="); System.out.println("====================="); list.stream().sorted((s1,s2)->{ int num =s1.length()-s2.length(); int num1 = num==0?s1.compareTo(s2):num; return num1; }).forEach(System.out::println); // map and mapToInt System.out.println("====================="); ArrayList<String> intList = new ArrayList<>(); list.add("10"); list.add("20"); list.add("30"); list.add("40"); intList.stream().map(s -> Integer.parseInt(s) ).forEach(System.out::println);
Step 3: terminate the operation
concept
The termination operation means that after this method is executed, the Stream stream cannot perform other operations.
Common methods
Void for each (consumer action): perform an action on each element of this flow
long count(): returns the number of elements in this stream
public class StreamDemo01 { public static void main(String[] args) { ArrayList<String> strings = new ArrayList<>(); strings.add("Zhou Enlai"); strings.add("Zhou Yuer"); strings.add("Big Joe"); strings.add("Little Joe"); strings.add("around"); strings.add("Zhuge Liang"); strings.add("Guan Yu"); // End operation: after this operation, the stream stream cannot perform other operations // forEach: performs an operation on each element of this flow // count: returns the number of elements in this stream strings.stream().forEach(System.out::println); long count = strings.stream().count(); System.out.println(count); }
Step 4: collection operation
concept
After the operation of using Stream flow for data is completed, the data in the Stream can be collected into the collection.
common method
R collect(Collector collector) collects the results into a collection
The tool class Collectors provides specific collection methods
public static Collector toList() collects elements into the List collection
public static Collector toSet() collects elements into the Set collection
**Public static collector tomap (function keymapper, function valuemapper) * * collects elements into the Map collection
package com.csf.streamIO; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class StreamDemo02 { public static void main(String[] args) { ArrayList<String> man = new ArrayList<>(); man.add("Zhou Xingchi"); man.add("Zhou Runfa"); man.add("Zhou Runfa"); man.add("Jackie Chan"); man.add("Jet Li"); man.add("Zhou Yu"); ArrayList<String> woman = new ArrayList<>(); woman.add("Zhang Manyu"); woman.add("Lin Qingxia"); woman.add("Liuyan"); woman.add("Wang Zuxian"); woman.add("Lin Zhiling"); Stream<String> stream = man.stream().filter(s -> s.startsWith("week")).distinct(); Stream<String> stringStream = woman.stream().limit(4).filter(s -> s.length() == 3); Stream<String> concat = Stream.concat(stringStream, stream); List<String> collect = concat.collect(Collectors.toList()); System.out.println(collect); // Array and collection exercises String[] str = {"Zhang San,21","Li Si,12","Wang Erma,22","Saturday,18","Liu Qi,20"}; Map<String,Integer> map = Stream.of(str).filter(s -> Integer.parseInt(s.split(",")[1]) >= 20) .collect(Collectors.toMap(s->s.split(",")[0],s->Integer.parseInt(s.split(",")[1]))); Set<String> strings = map.keySet(); for (String key:strings){ Integer integer = map.get(key); System.out.println(key+":"+integer); } } }
Some method examples may not be listed in full. Draw inferences from one instance.
Learning record!!!