catalogue
Common generation methods of Stream
Stream intermediate operation method
Other common intermediate methods
Stream termination operation method
Collection method - toList and toSet
Variable parameter
-
Introduction to variable parameters
-
Variable parameters are also called variable number of parameters. If they are used as formal parameters of a method, the number of method parameters is variable
-
The parameter type of the method has been determined, and the number is uncertain. We can use variable parameters
-
-
Variable parameter definition format
Modifier return value type method name (data type... Variable name) {} public static int sum(int... a) { }
-
Precautions for variable parameters
-
The variable here is actually an array
-
If a method has multiple parameters, including variable parameters, the variable parameters should be placed last
-
public static void main(String[] args) { System.out.println(sum(10, 20)); System.out.println(sum(10, 20, 30)); System.out.println(sum(10, 20, 30, 40)); System.out.println(sum(10,20,30,40,50)); System.out.println(sum(10,20,30,40,50,60)); System.out.println(sum(10,20,30,40,50,60,70)); System.out.println(sum(10,20,30,40,50,60,70,80,90,100)); } // public static int sum(int b,int... a) { // return 0; // } public static int sum(int... a) { int sum = 0; for(int i : a) { sum += i; } return sum; }
Create immutable collection
Method introduction
-
In the List, Set and Map interfaces, there are of methods, which can create an immutable Set
-
This collection cannot be added, deleted or modified
-
However, it can be combined with the parameter structure of the set to realize the batch addition of the set
-
-
In the Map interface, there is also an ofEntries method to improve the readability of the code
-
First, the key value pair will be encapsulated into an Entry object, and then the Entry object will be added to the collection
-
Static < E > List < E > of(E... elements) creates a list collection object with a specified element
Static < E > Set < E > of(E... elements) creates a Set set object with a specified element
Static < K, V > Map < K, V > of(E... elements) creates a Map collection object with a specified element
public static void main(String[] args) { /* static <E> List<E> of(E...elements) Creates a List collection object with the specified element static <E> Set<E> of(E...elements) Creates a Set collection object with the specified element static <K , V> Map<K,V> of(E... elements) Creates a Map collection object with the specified element */ //method1(); //method2(); //method3(); //method4(); } private static void method4() { Map<String, String> map = Map.ofEntries( Map.entry("zhangsan", "Jiangsu"), Map.entry("lisi", "Beijing")); System.out.println(map); } private static void method3() { Map<String, String> map = Map.of("zhangsan", "Jiangsu", "lisi", "Beijing", "wangwu", "Tianjin"); System.out.println(map); } private static void method2() { //There cannot be duplicate elements in the parameters passed. Set<String> set = Set.of("a", "b", "c", "d","a"); System.out.println(set); } private static void method1() { List<String> list = List.of("a", "b", "c", "d"); System.out.println(list); //list.add("Q"); //list.remove("a"); //list.set(0,"A"); //System.out.println(list); // ArrayList<String> list2 = new ArrayList<>(); // list2.add("aaa"); // list2.add("aaa"); // list2.add("aaa"); // list2.add("aaa"); //Batch addition of collections. //The first is by calling list Of method to create an immutable set. The formal parameter of the of method is a variable parameter. //Then create an ArrayList set and add all the data in the immutable set to the ArrayList. ArrayList<String> list3 = new ArrayList<>(List.of("a", "b", "c", "d")); System.out.println(list3); }
Stream stream
Experience Stream
Case requirements:
Complete the creation and traversal of the collection according to the following requirements
-
Create a collection to store multiple string elements
-
Store all elements starting with "Zhang" in the collection into a new collection
-
Store the elements of length 3 in the set beginning with "Zhang" into a new set
-
Traverse the set obtained in the previous step
Original method presentation:
public static void main(String[] args) { //Batch addition of collections ArrayList<String> list1 = new ArrayList<>(List.of("Zhang Sanfeng" ,"zhang wuji","Zhang Cuishan","Wang Er Ma Zi","chief counsellor of Liu Bang","Xie Guangkun")); //list.add() //Traverse list1 and add the elements starting with Zhang to list2. ArrayList<String> list2 = new ArrayList<>(); for (String s : list1) { if(s.startsWith("Zhang")){ list2.add(s); } } //Traverse the list2 set, add the elements with length of 3 to list3. ArrayList<String> list3 = new ArrayList<>(); for (String s : list2) { if(s.length() == 3){ list3.add(s); } } for (String s : list3) { System.out.println(s); } }
Use Stream stream sample code:
public static void main(String[] args) { //Batch addition of collections ArrayList<String> list1 = new ArrayList<>(List.of("Zhang Sanfeng" ,"zhang wuji","Zhang Cuishan","Wang Er Ma Zi","chief counsellor of Liu Bang","Xie Guangkun")); //Stream stream list1.stream().filter(s->s.startsWith("Zhang")) .filter(s->s.length() == 3) .forEach(s-> System.out.println(s)); }
Benefits of Stream flow
-
Directly reading the literal meaning of the code can perfectly display the semantics of irrelevant logical methods: obtaining stream, filtering surname Zhang, filtering length of 3, printing one by one
-
Stream stream introduces a true functional programming style into Java
-
Concise code
Common generation methods of Stream
The idea of Stream flow:
Three kinds of core methods of Stream
-
Get Stream stream
-
Create a pipeline and put the data on the pipeline for operation
-
-
Intermediate method
-
Operation on pipeline
-
After one operation, you can continue with other operations
-
-
Termination method
-
A Stream stream can only have one termination method
-
Is the last operation on the pipeline
-
How to get the Stream
1. Single column Collection: generates a stream using the default method stream() in the Collection
2. Double column Set: get the Set set through the ketSet or entrySet, and then get the Stream stream (indirectly)
3. Array: the static method stream() in Arrays generates a stream
4. Several data of the same data type: through stream Of (t... Values) generates a flow, and the parameters are variable parameters
public static void main(String[] args) {} //4. Several data of the same data type: through stream Of (t... Values) generates a flow, and the parameters are variable parameters private static void method04() { Stream.of(1,2,3,4,5).forEach(num -> System.out.println(num)); Stream.of("aa","bb","cc").forEach(s -> System.out.println(s)); } //3. Array: the static method stream() in Arrays generates a stream private static void method03() { int[] arr = {11,22,33}; Arrays.stream(arr).forEach(num -> System.out.println(num)); } //2. Two column Set: get the Set set through the ketSet or entrySet, and then get the Stream stream (indirectly) private static void method02() { HashMap<String,String> map = new HashMap<>(); map.put("001","Liu Bei"); map.put("002","Guan Yu"); map.put("003","Fei Zhang"); //Get all keys through the ketSet and put them into the Stream stream map.keySet().stream().forEach((key)-> System.out.println(key)); //All keys //Get all key value pairs through entrySet and put them into the Stream stream map.entrySet().stream().forEach((kv) -> System.out.println(kv)); //All key value pairs } //1. Single column Collection: use the default method stream() in the Collection to generate a stream private static void method01() { ArrayList<String> list = new ArrayList<>(List.of("Zhang San","Li Si","Wang Wu")); //Generate flow Stream<String> stream = list.stream(); //Call foreach, receive the Consumer implementation class object with the parameter, and rewrite accept to print the result stream.forEach(new Consumer<String>() { @Override public void accept(String s) { System.out.println(s); } }); //Simplify anonymous inner classes stream.forEach(s -> System.out.println(s)); }
Stream intermediate operation method
Method name | explain |
---|---|
Stream<T> filter(Predicate predicate) | Used to filter the data in the convection |
Stream<T> limit(long maxSize) | Returns the stream composed of elements in this 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 |
static <T> Stream<T> concat(Stream a, 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)) |
Intermediate method filter
Stream < T > filter (percolate): used to filter the data in the convection
There is only one test method in the Perdicate interface
boolean test(T t); Judge the data in the convection in turn and return the result of boolean type
public static void main(String[] args) { //Test data: filter the string with reserved length of 3 ArrayList<String> list = new ArrayList<>(); list.add("Zhang Yide"); list.add("xuande "); list.add("Guan Yu"); list.add("Fei Zhang"); list.add("LV Fengxian"); //Stream < T > filter (predict): used to filter the data in the stream // 1.filter gets the data in the stream list.stream().filter(new Predicate<String>() { @Override public boolean test(String s) { // 2. In the test method, if the returned result is true, the data will be retained, // If the returned result is false, the data will be filtered boolean result = s.length() == 3; return result; } }).forEach(s -> System.out.println(s)); // 3. Simplify the above code list.stream().filter( (String s) -> { boolean result = s.length() == 3; return result; } ).forEach(s -> System.out.println(s)); // 4. Simplify the above code list.stream().filter((String s) -> s.length() == 3) .forEach((String s) -> System.out.println(s)); }
Other common intermediate methods
Other intermediate methods
1. Number of data intercepted by < maxlong > parameter:
2. Stream < T > skip (long n): skip the data of the specified number of parameters
3. Static Stream < T > concat (Stream a, Stream b): merge the specified two streams. The static method passes through Stream
Direct call
4. Stream<T> distinct(); De duplication, the bottom layer depends on hashCode and equals methods
Limit & skip code demonstration
public static void main(String[] args) { //Create a collection to store multiple string elements ArrayList<String> list = new ArrayList<String>(); list.add("Lin Qingxia"); list.add("Zhang Manyu"); list.add("Wang Zuxian"); list.add("Liuyan"); list.add("Zhang Min"); list.add("zhang wuji"); //Requirement 1: take the first four data to form a flow 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 flow obtained from requirement 1 and requirement 2, and output the results on the console // Stream.concat(s1,s2).forEach(s-> System.out.println(s)); //Requirement 4: merge the streams obtained from requirement 1 and requirement 2, and output the results on the console. It is required that the string elements cannot be repeated Stream.concat(s1,s2).distinct().forEach(s-> System.out.println(s)); }
Concat & distinct code demonstration
public static void main(String[] args) { //Create a collection to store multiple string elements ArrayList<String> list = new ArrayList<String>(); list.add("Lin Qingxia"); list.add("Zhang Manyu"); list.add("Wang Zuxian"); list.add("Liuyan"); list.add("Zhang Min"); list.add("zhang wuji"); //Requirement 1: take the first four data to form a flow 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 flow obtained from requirement 1 and requirement 2, and output the results on the console // Stream.concat(s1,s2).forEach(s-> System.out.println(s)); //Requirement 4: merge the streams obtained from requirement 1 and requirement 2, and output the results on the console. It is required that the string elements cannot be repeated Stream.concat(s1,s2).distinct().forEach(s-> System.out.println(s)); }
Stream termination operation method
Concept:
The end operation means that after this method is executed, the Stream stream cannot perform other operations
Common methods:
Method name | explain |
---|---|
void forEach(Consumer action) (there is only one abstract method in the Consumer interface.) | Perform operations on each element of this flow |
long count() | Returns the number of elements in this stream |
public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Zhang Sanfeng"); list.add("zhang wuji"); list.add("Zhang Cuishan"); list.add("Wang Er Ma Zi"); list.add("chief counsellor of Liu Bang"); list.add("Xie Guangkun"); //method1(list); // long count(): returns the number of elements in this stream long count = list.stream().count(); System.out.println(count); } private static void method1(ArrayList<String> list) { // Void for each (consumer action): perform an action on each element of this flow // Method void accept (T) in the Consumer interface: perform this operation on the given parameter //At the bottom of the forEach method, each data in the stream will be obtained circularly //And call the accept method circularly, and pass each data to the accept method //s represents each data in the stream in turn //Therefore, we just need to write the business logic in the accept method list.stream().forEach( new Consumer<String>() { @Override public void accept(String s) { System.out.println(s); } } ); System.out.println("===================="); //Simplified format of lambda expression //Because there is only one accept method in the interface list.stream().forEach( (String s)->{ System.out.println(s); } ); System.out.println("===================="); //lambda expressions can be further simplified list.stream().forEach(s->System.out.println(s)); }
Stream - data in the data source cannot be modified directly
Note: flow operations can only modify the data in the flow, not the data in the data source directly
Requirements: filter elements and traverse collections
Define a set and add integer elements 1-10
Delete the odd number in the collection, keep only the even number elements, and traverse the collection
public static void main(String[] args) { //Define a set and add integer elements 1-10 // ArrayList<Integer> list = new ArrayList<>(); // for (int i = 1; i < 10; i++) { // list.add(i); // } //Define a set and add integer elements 1-10 ArrayList<Integer> list = new ArrayList<>( List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); //Delete the odd number in the collection, keep only the even number elements, and traverse the collection list.stream().filter((num) -> (num % 2 == 0)) .forEach(num -> System.out.print(num + " ")); //2 4 6 8 10 System.out.println(); //Line feed //Note: flow operations can only modify the data in the flow, not the data in the data source directly //Proof: print data source set after filtering System.out.println(list); //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }
Collection method
Thinking:
A stream operation can only modify the data in the stream, not the data in the data source directly
After using the intermediate method, what should I do if I want to store and collect the data?
Concept:
The data in the Stream can be collected into the collection after the operation of using the Stream flow for the data is completed
Collection method of Stream
Method name | explain |
---|---|
R collect(Collector collector) | Collect the results into a collection |
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 set |
public static Collector toMap(Function keyMapper,Function valueMapper) | Collect elements into the Map collection |
Collection method - toList and toSet
The tool class Collector provides specific collection methods
1. public static<T> Collector toList(); Collect elements into the List collection
2. public static<T> Collector toSet(); Collect elements into the Set collection
public static void main(String[] args) { //Define a set and add integer elements 1-10 ArrayList<Integer> list1 = new ArrayList<>(); for (int i = 1; i < 10; i++) { list1.add(i); } //Store duplicate elements list1.add(10); list1.add(10); list1.add(10); list1.add(10); //Filter out even elements list1.stream().filter(num -> num % 2 == 0) .forEach(num -> System.out.println(num)); //1. public static<T> Collector toList(); Collect elements into the List collection //filter is only responsible for filtering. If you continue to call the forEach termination method, you will not be able to obtain the filtered data List<Integer> list = list1.stream().filter(num -> num % 2 == 0) //collect is responsible for collecting and storing the filtered data into the specified container (List/Set/Map) .collect(Collectors.toList()); System.out.println(list); //[2, 4, 6, 8, 10, 10, 10, 10, 10] the list set allows repetition //2. public static<T> Collector toSet(); Collect elements into the Set collection Set<Integer> set = list1.stream().filter(num -> num % 2 == 0) .collect(Collectors.toSet()); System.out.println(set); //[2, 4, 6, 8] Set cannot be duplicated }
Collection method - toMap
The tool class Collector provides specific collection methods
3. Collectors. Tomap (if the key is obtained, if the value is obtained); Collect elements into the Map collection
demand
Create an ArrayList collection and add the following string data. The key is name and the value is age
"zhangsan,23"
"lisi,24"
"wangwu,25"
Filter and retain people aged 24 or older, and collect the results into the Map collection
public class Demo { public static void main(String[] args) { //Create an ArrayList collection and add elements ArrayList<String> list = new ArrayList<>(); list.add("zhangsan,23"); list.add("lisi,24"); list.add("wangwu,25"); //Put input into stream Map<String, Integer> map = list.stream().filter( s -> { //The parameter s is each string element, according to the comma String[] arr = s.split(","); //Get the second element in the returned array, which is age, and convert it to int type int age = Integer.parseInt(arr[1]); //Return judgment result return age >= 24; } ).collect(Collectors.toMap( /* List And Set are single column sets. You can store the whole array directly, so toList and toSet are empty parameters Map The set is a double column set. The computer does not know who is the key and who is the value, so we need to give the implementation manually Collectors.toMap(If get key, if get value); Collect elements into the Map collection */ //Parameter 1: s represents the data obtained from the stream in turn. According to the lambda expression, cut the key from S (String s) -> { String name = s.split(",")[0]; return name; }, //Parameter 2: s represents the data obtained from the stream in turn. According to the lambda expression, cut the value from S (String s) -> { int age = Integer.parseInt(s.split(",")[1]); return age; } )); //Print map set content System.out.println(map); //{lisi=24, wangwu=25} } }
Extended case landlords
Extended case:
Through the program to realize the shuffling, licensing, card watching and other operations in the process of fighting the landlord
1. To create a card box is to define a collection object, which is implemented with ArrayList
2. Create an array to store decors and numbers
3. Traverse two arrays through loop nesting. The outer loop controls colors and the memory loop controls numbers
4. Splice the cards according to color+number and put them into the card box
5. Deposit in big and small king
6. shuffle the cards
7. Create three players
8. Traverse the card box to deal cards
9. Get each poker card
10. If it is the last three cards, it will be dealt as the bottom card
11. According to the law that the remainder of 3 is equal to 0,1,2 through the index, deal cards to three players respectively
12. Provide a way to look at cards
13. Call the card watching method to watch cards
public static void main(String[] args) { // 1. Create a card box, that is, define a collection object and implement it with ArrayList ArrayList<String> list = new ArrayList<>(); // 2. Create an array for storing decors and numbers String[] colors = {"♠", "♥", "♣", "♦"}; String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "k", "A"}; // 3. Traverse two arrays through loop nesting. The outer loop controls colors and the memory loop controls numbers for (String color : colors) { for (String number : numbers) { //4. Splice the cards according to color+number and put them into the card box list.add(color + number); } } // 5. Deposit in big and small king list.add("king"); list.add("Xiao Wang"); //System.out.println(list); //System.out.println(list.size()); // 6. Shuffle Collections.shuffle(list); //System.out.println(list); // 7. Create three players ArrayList<String> player1 = new ArrayList<>(); ArrayList<String> player2 = new ArrayList<>(); ArrayList<String> player3 = new ArrayList<>(); ArrayList<String> dp = new ArrayList<>(); // 8. Traverse the card box for licensing for (int i = 0; i < list.size(); i++) { // 9. Get each card poker String poker = list.get(i); // 10. If it is the last three cards, it will be dealt as the bottom card if (i >= list.size() - 3) { dp.add(poker); } else if (i % 3 == 0) { // 11. According to the rule that the remainder of 3 is equal to 0,1,2 through the index, deal cards to three players respectively player1.add(poker); } else if (i % 3 == 1) { player2.add(poker); } else if (i % 3 == 2) { player3.add(poker); } } // 13. Call the card watching method to watch cards look("Luo Xiang",player1); look("Zhang San",player2); look("Wu Yanzu",player3); look("a hand",dp); } // 12. Provide ways to look at cards public static void look(String name, ArrayList<String> list) { System.out.print(name + "Your card is: "); for (String poker : list) { System.out.print(poker + " "); } System.out.println(); //Line feed }
Extended case (upgrade):
Through the program to realize the shuffling, licensing, card watching and other operations in the process of fighting the landlord
The cards on each hand are required to be arranged in order
Idea:
1. Define the HashMap set, key storage index, value storage decor and number
2. Define the ArrayList set synchronization storage index define the ArrayList set synchronization storage index
3. Create an array to store decors and numbers
4. The variable index is defined to store the index. It will be incremented by 1 after each storage
7. Add size king, don't forget to modify the index and store
8. Shuffle only needs to shuffle the index (ArrayList set)
9. When dealing cards, the player's cards are stored in the TreeSet set to complete the sorting
10. Traverse the ArrayList collection where the index is stored and send the index
11. If it is the last three cards (index), it will be dealt as the bottom card
12. According to the law, deal cards to three players respectively (index)
13. Provide a method of watching cards, which receives the player's name, stores the indexed TreeSet set, and the card box HashMap
Print name
Traverses the TreeSet collection where the index is stored
Get the corresponding values (colors and numbers) according to the index (key)
Print results
14. Call the card watching method
public static void main(String[] args) { // 1. Define the HashMap set key to store the index, and the value to store the decor and number HashMap<Integer, String> map = new HashMap<>(); // 2. Define the ArrayList set and store the index synchronously ArrayList<Integer> list = new ArrayList<>(); // 3. Create an array for storing decors and numbers String[] colors = {"♠", "♥", "♣", "♦"}; String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "k", "A"}; // 4. Define the variable index to store the index, which will be incremented by 1 after each storage int index = 0; for (String color : colors) { for (String number : numbers) { // 5. The key stores the index, and the value stores the decor and number map.put(index, color + number); // 6. Store the key synchronization into the ArrayList set list.add(index); index++; } } // 7. Add the size king. Don't forget to modify the index and store it map.put(index, "king"); list.add(index); index++; map.put(index, "Xiao Wang"); list.add(index); // No, because the cards have been saved // System.out.println(index); //53 // 8. Shuffle only needs to shuffle the index (ArrayList set) Collections.shuffle(list); // 9. When dealing cards, the player's cards are stored in the TreeSet set to complete the sorting TreeSet<Integer> player1 = new TreeSet<>(); TreeSet<Integer> player2 = new TreeSet<>(); TreeSet<Integer> player3 = new TreeSet<>(); TreeSet<Integer> dp = new TreeSet<>(); // 10. Traverse the ArrayList set where the index is stored and send the index for (int i = 0; i < list.size(); i++) { int pokerIndex = list.get(i); // 11. If the index is the last three cards, then if (i >= list.size() - 3) { dp.add(pokerIndex); } else if (i % 3 == 0) { // 12. Deal cards (index) to three players according to the law player1.add(pokerIndex); } else if (i % 3 == 1) { player2.add(pokerIndex); } else if (i % 3 == 2) { player3.add(pokerIndex); } } // 14. Call the card reading method look("Luo Xiang", player1, map); look("Zhang San", player2, map); look("Wu Yanzu", player3, map); look("a hand", dp, map); } // 13. Provide a card watching method, which receives the player's name, stores the indexed TreeSet set, and the card box HashMap public static void look(String name, TreeSet<Integer> set, HashMap<Integer, String> map) { System.out.print(name + "Your card is: "); // Traverses the TreeSet collection where the index is stored for (Integer key : set) { // Get the corresponding values (colors and numbers) according to the index (key) String value = map.get(key); // Print results System.out.print(value + " "); } System.out.println(); //Line feed }