(I) Fundamentals of Java language
(II) Java object oriented programming
(III) Of Java core class libraries (common API s, string classes, collection classes, generics)
(IV) Of Java core class library (exception mechanism)
(V) Java core class library (character set / code set, File class, recursion, IO stream: byte stream, character stream, special operation stream)
(VI) Of Java core class library (reflection mechanism: class loader and reflection)
(VII) Of Java core class library (Lambda expression)
(VIII) Of Java core class library (interface composition update, method reference, functional interface)
(IX) Of Java core class library (Stream stream: generation, intermediate, termination and collection operations)
(x) Of Java core class library (multithreading: realizing multithreading and thread synchronization)
1 Stream
- Experience Stream
- demand
package test; import java.lang.reflect.Array; import java.util.ArrayList; public class Demo { public static void main(String[] args) { //Create a collection to store multiple characters ArrayList<String> list = new ArrayList<>(); list.add("Xiao Hei"); list.add("zhang wuji"); list.add("panda"); list.add("Zhang Tianfeng"); list.add("Xiaobai"); list.add("Fei Zhang"); //Store all data beginning with "Zhang" in the set into a new set ArrayList<String> zhanglist = new ArrayList<>(); for(String s:list) { if(s.startsWith("Zhang")) { zhanglist.add(s); } } // System.out.println(zhanglist); // [Zhang Wuji, Zhang Tianfeng, Zhang Fei] //Save "Zhang" with a length of 3 at the beginning to a new set ArrayList<String> threelist = new ArrayList<>(); for(String s:zhanglist) { if(s.length()==3) { threelist.add(s); } } for(String s:threelist) { System.out.println(s); // zhang wuji // Zhang Tianfeng } //Stream stream list.stream().filter(s->s.startsWith("Zhang")).filter(s->s.length()==3); // zhang wuji // Zhang Tianfeng } }
- Use Stream to complete the filtering operation
- list. stream(). Filter (s - > s.startswith ("Zhang")) filter(s->s.length()==3);
- Directly reading the literal meaning of the code can perfectly display the semantics of irrelevant logical methods: generating flow, filtering surname Zhang, filtering length of 3, and printing one by one
- Stream stream introduces a true functional programming style into Java
1.1 generation method of stream
- Common generation methods of Stream
- 1. A Collection of the Collection system can generate a stream using the default method stream(): default stream < E > stream()
- 2. The collection of Map system generates an indirect flow
- 3. Array can generate Stream through static method of Stream interface: of (T... values)
package test; import java.util.*; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { //1. A Collection of the Collection system can generate a stream using the default method stream(): default stream < E > stream() List<String> list = new ArrayList<>(); Stream<String> listStream = list.stream(); Set<String> set = new HashSet<>(); Stream<String> setStream = set.stream(); //2. The collection of Map system generates an indirect flow Map<String,Integer> map = new HashMap<>(); Stream<String> keyStream = map.keySet().stream(); //The KeySet() method gets a Set set Stream<Integer> valueStream = map.values().stream(); Stream<Map.Entry<String, Integer>> entryStream = map.entrySet().stream(); //3. Array can generate Stream through static method of Stream interface: of (T... values) String[] strArray = {"java","python","scala"}; Stream<String> strArrayStream1 = Stream.of(strArray); Stream<String> strArrayStream2 = Stream.of("java","python"); Stream<Integer> integerStream = Stream.of(10, 20, 30); } }
- How to use Stream
Method name | explain |
---|---|
list.stream() | Generate streams: generate streams from data sources (collections, arrays, etc.) |
filter() | Intermediate operation: a stream can be followed by zero or more intermediate operations. Its main purpose is to open the stream, make a certain degree of data filtering mapping, and then return a new stream for the next operation |
forEach() | Termination operation: a stream can only have one termination operation. When this operation is executed, the stream will be used "light" and can no longer be operated. Therefore, this must be the last operation of the stream |
1.2 filter of stream intermediate operation
-
Stream < T > filter (predict): used to filter the data in the stream
-
Boolean test (T) method in predict interface: judge the given parameter and return a Boolean value
-
example
package test; import java.util.ArrayList; public class Demo { public static void main(String[] args) { //Create a collection to store multiple elements ArrayList<String> list = new ArrayList<>(); list.add("Xiao Hei"); list.add("zhang wuji"); list.add("panda"); list.add("Zhang Tianfeng"); list.add("Xiaobai"); list.add("Fei Zhang"); //Need 1: output the list starting with Zhang on the console list.stream().filter(s -> s.startsWith("Zhang")).forEach(System.out::println); System.out.println("--------"); // zhang wuji // Zhang Tianfeng // Fei Zhang //Need 2: output the element with length 3 in the list set list.stream().filter(s -> s.length() == 3).forEach(System.out::println); System.out.println("--------"); // zhang wuji // panda // Zhang Tianfeng //Requirement 3: output the beginning with Zhang and length of 3 on the console list.stream().filter(s -> s.startsWith("Zhang")).filter(s -> s.length() == 3).forEach(System.out::println); // zhang wuji // Zhang Tianfeng } }
1.3 limit and skip of stream intermediate operations
- Stream < T > limit (long maxsize): returns the stream composed of elements in the stream and intercepts the data of the specified number of parameters before
- Stream < T > skip (long n): skip the data of the specified number of parameters and return the stream composed of the remaining elements of the stream
- example:
package test; import java.util.ArrayList; public class Demo { public static void main(String[] args) { //Create a collection to store multiple elements ArrayList<String> list = new ArrayList<>(); list.add("Xiao Hei"); list.add("zhang wuji"); list.add("panda"); list.add("Zhang Tianfeng"); list.add("Xiaobai"); list.add("Fei Zhang"); //Need 1: take the first three data and output it on the console list.stream().limit(3).forEach(System.out::println); System.out.println("---------"); // Xiao Hei // zhang wuji // panda //Requirement 2: skip 3 elements and output the rest on the console list.stream().skip(3).forEach(System.out::println); System.out.println("---------"); // Zhang Tianfeng // Xiaobai // Fei Zhang //Requirement 3: skip 2 elements and output the first two of the remaining elements list.stream().skip(2).limit(2).forEach(System.out::println); // panda // Zhang Tianfeng } }
1.4 concat and distinct of stream intermediate operations
-
static <T> Stream<T> concat(Stream а, Stream b): merge two streams a and B into one stream
-
Stream < T > distinct(): returns a stream composed of different elements of the stream (according to Object.equals(Object))
-
example:
package test; import java.util.ArrayList; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { //Create a collection to store multiple elements ArrayList<String> list = new ArrayList<>(); list.add("Xiao Hei"); list.add("zhang wuji"); list.add("panda"); list.add("Zhang Tianfeng"); list.add("Xiaobai"); list.add("Fei Zhang"); //Requirement 1: take the first four data to form a stream Stream<String> s1 = list.stream().limit(4); //Requirement 2: skip two data to form a stream Stream<String> s2 = list.stream().skip(2); //Requirement 3: merge the streams obtained from the results of 1 and 2 and output them // Stream.concat(s1,s2).forEach(System.out::println); // Xiao Hei // zhang wuji // panda // Zhang Tianfeng // panda // Zhang Tianfeng // Xiaobai // Fei Zhang //Requirement 4: combine the streams obtained from the results of 1 and 2 and output them. It is required that the results are not repeated Stream.concat(s1, s2).distinct().forEach(System.out::println); // Xiao Hei // zhang wuji // panda // Zhang Tianfeng // Xiaobai // Fei Zhang } }
Middle stream operation sort 1.5
- Stream < T > sorted(): returns the stream composed of the elements of this stream, sorted according to the natural order
- Stream < T > sort ể d(Comparator comparator): returns the stream composed of the elements of this stream, sorted according to the provided Comparator
- example
package test; import java.util.ArrayList; public class Demo { public static void main(String[] args) { //Create a collection to store multiple elements ArrayList<String> list = new ArrayList<>(); list.add("b123"); list.add("a1"); list.add("f1234"); list.add("c12"); list.add("e12345"); list.add("d12345"); //Required 1: output on the console in alphabetical order list.stream().sorted().forEach(System.out::println); // a1 // b123 // c12 // d12345 // e12345 // f1234 //Requirement 2: sort according to the string length, which is the same list.stream().sorted((s1, s2) -> { int num1 = s1.length() - s2.length(); int num2 = num1 == 0 ? s1.compareTo(s2) : num1; return num2; }).forEach(System.out::println); // a1 // c12 // b123 // f1234 // d12345 // e12345 } }
1.6 map and mapToInt of stream intermediate operations
- <R> Stream < R > map (function mapper): returns a stream consisting of the results of a given function applied to this stream element
Method in Function interface - R apply (T) - IntStream mapToInt(ToIntFunction mapper): returns an InStream containing the results of the elements applied by the given function to this stream
Instream: indicates the original stream
Method in TolntFunction interface - int applyAslnt(T value) - example:
package test; import java.util.ArrayList; public class Demo { public static void main(String[] args) { //Create a collection to store multiple elements ArrayList<String> list = new ArrayList<>(); list.add("10"); list.add("20"); list.add("30"); list.add("40"); list.add("50"); //Required: convert the string in the collection to an integer and output it on the console // list.stream().map(s->Integer.parseInt(s)).forEach(System.out::println); //Method reference // list.stream().map(Integer::parseInt).forEach(System.out::println); // list.stream().mapToInt(Integer::parseInt).forEach(System.out::println); // 10 // 20 // 30 // 40 // 50 //Method in InStream: int sum() returns the sum of elements in the stream int result = list.stream().mapToInt(Integer::parseInt).sum(); System.out.println(result); //150 } }
1. 7 forEach and count of stream termination operation
-
Common termination operation methods of Stream
- Void for each (consumer action): perform an action on each element of this flow
Method in the Consumer interface - void accept (T): perform this operation on the given parameter - long count(): returns the number of elements in this stream
- Void for each (consumer action): perform an action on each element of this flow
-
example
package test; import java.util.ArrayList; public class Demo { public static void main(String[] args) { //Create a collection to store multiple elements ArrayList<String> list = new ArrayList<>(); list.add("Xiao Hei"); list.add("zhang wuji"); list.add("panda"); list.add("Zhang Tianfeng"); list.add("Xiaobai"); list.add("Fei Zhang"); //Requirement 1: Elements in the output set list.stream().forEach(System.out::println); // Xiao Hei // zhang wuji // panda // Zhang Tianfeng // Xiaobai // Fei Zhang //Demand 2: count the number of sheets beginning with sheets long count = list.stream().filter(s -> s.startsWith("Zhang")).count(); System.out.println(count); //3 } }
1.8 Stream collection
- After using the Stream stream method to operate the data, I want to collect the data in the Stream into the collection. What should I do?
- Collection method of Stream
Method name | explain |
---|---|
R collect(Collector collector) | But the parameter of this collection method is a Collector interface |
- The tool class Collectors provides specific collection methods
Method name | explain |
---|---|
public static <T> Collector toList() | Collect elements into the List collection |
public static <T> Collector toSet() | Collect elements into the Set collection |
public static Collector toMap(Function keyMapper,Function valueMapper) | Collect the metadata into the Map set |
- example
package test; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { //Create a list collection to store multiple elements ArrayList<String> list = new ArrayList<>(); list.add("Xiao Hei"); list.add("panda"); list.add("Fei Zhang"); list.add("lesser panda"); //Requirement 1: get a stream with a name of three words Stream<String> listStream = list.stream().filter(name -> name.length() == 3); //Requirement 2: store the data obtained by Stream operation into the list set and traverse it List<String> names = listStream.collect(Collectors.toList()); for (String name : names) { System.out.println(name); // panda // lesser panda } //Create Set collection object Set<Integer> set = new HashSet<>(); set.add(10); set.add(20); set.add(30); set.add(40); //Requirement 3: get streams older than 25 Stream<Integer> setStream = set.stream().filter(age -> age > 25); //Requirement 4: store the data obtained by Stream operation into the set set and traverse it Set<Integer> ages = setStream.collect(Collectors.toSet()); for (Integer age : ages) { System.out.println(age); // 40 // 30 } //Defines an array of strings consisting of names and ages String[] strArray = {"Xiao Hei,10", "Xiaobai,20", "lesser panda,30", "panda,40"}; //Requirement 5: get the stream older than 25 in the string array Stream<String> arrayStream = Stream.of(strArray).filter(s -> Integer.parseInt(s.split(",")[1]) > 28); //Requirement 6: store and traverse the data obtained by Stream operation into the map set, with name as the key and age as the value Map<String, Integer> map = arrayStream.collect(Collectors.toMap(s -> s.split(",")[0], s -> Integer.parseInt(s.split(",")[1]))); Set<String> keySet = map.keySet(); for (String key : keySet) { Integer vlaue = map.get(key); System.out.println(key + "," + vlaue); // Giant panda, 40 // Panda, 30 } } }