Examples of solving tasks on data streams Stream API
Contents
- 1. Determining the number of even numbers in the data stream. Example
- 2. Working with streams of strings. Search in a string. Example
- 3. Sorting strings. Example
- Related topics
Search other Web sites:
1. Determining the number of even numbers in the data stream. Example
Task. For any set of randomly generated numbers, you need to determine the number of paired ones. To solve the problem, use the tools of the Stream API programming interface.
Solution. The solution to the problem is displayed in the static method DemoStream(), which is called from the main() function.
import java.util.stream.*; import java.util.*; import java.util.function.*; public class TrainStreamAPI { public static void DemoStream() { // Task. For any set of randomly generated numbers, // you need to determine the number of paired ones. // 1. Create data stream from random array of numbers ArrayList<Integer> AL = new ArrayList<Integer>(); int number; Random rnd = new Random(); for (int i=0; i<10; i++) { number = rnd.nextInt() % 100; AL.add(number); } System.out.println("Array AL:"); System.out.println(AL); // 2. Determine the number of paired numbers. Method 1. // 2.1. Create stream from AL array - stream() method Stream<Integer> st = AL.stream(); // 2.2. Declare a reference to the Predicate<Integer> // standard functional interface Predicate<Integer> fn; // this reference will be passed to the filter() method // 2.3. Assign a lambda expression to the reference that determines if the number is even fn = (n) -> (n%2) == 0; // 2.4. Call the filter() method, which selects only pairs of numbers from stream st Stream<Integer> resStream = st.filter(fn); // 2.5. Print the number of paired numbers System.out.println("n = " + resStream.count()); // 3. Determine the number of paired numbers. Method 2 - quick way int n2 = (int)(AL.stream().filter((n)->(n%2)==0)).count(); System.out.println("n2 = " + n2); } public static void main(String[] args) { DemoStream(); } }
The result of the program
Array AL: [-79, 99, -83, -75, -78, -22, -57, 84, 11, 15] n = 3 n2 = 3
⇑
2. Working with streams of strings. Search in a string. Example
Task. Many names of employees are set. Develop a program that displays all surnames starting with the letter “J”. Solve the problem using the Stream API.
Solution.
import java.util.stream.*; import java.util.*; import java.util.function.*; public class TrainStreamAPI { public static void DemoStream() { // Task. Many names of employees are set. // Develop a program that displays all the names that begin with the letter 'J' // 1. Organize the input of surnames from the keyboard. // End of input - empty string "" Scanner scanner = new Scanner(System.in); String s; ArrayList<String> AL = new ArrayList<String>(); System.out.println("Enter names: "); while (true) { System.out.print("name = "); s = scanner.nextLine(); if (s.equals("")==true) break; AL.add(s); } System.out.println(); // 2. Display an array of entered names System.out.println("AL = " + AL); // 3. Calculate the number of names that start with 'J' // 3.1. Declare a reference to the functional interface Predicate<T> Predicate<String> fn; // 3.2. Set lambda expression for fn fn = (str) -> { if (str.charAt(0)=='J') return true; return false; }; // 3.3. Convert AL to stream of strings Stream<String> stream = AL.stream(); // 3.4. Get the filtered stream // according to the predicate defined in fn() Stream<String> resStream = stream.filter(fn); // 3.5. Print the number of names starting with J System.out.println("count = " + resStream.count()); } public static void main(String[] args) { DemoStream(); } }
The result of the program
Enter names: name = abc name = Jlskjf name = JJ name = lskdjlsk name = sldkfjs name = dflskdj name = sdsd name = ss name = AL = [abc, Jlskjf , JJ, lskdjlsk, sldkfjs, dflskdj, sdsd, ss] count = 2
⇑
3. Sorting strings. Example
Task. An array of strings is given. Sort the strings in lexicographic order using StreamAPI.
Solution. The text of the program that solves this problem is as follows.
import java.util.*; import java.util.stream.*; import java.util.function.*; public class StreamAPI { public static void main(String[] args) { // 1. Declare an arbitrary array of strings String[] AS = { "abcd", "bcfk", "def", "jklmn", "jprst", "afc", "ambn", "kmk", "qrbd", "jus" }; // 2. Create collection from array of strings ArrayList<String> AL = new ArrayList<String>(AS.length); for (int i=0; i<AS.length; i++) AL.add(i, AS[i]); // 3. Create data stream from collection AL Stream<String> stream = AL.stream(); // 4. Sort stream in natural order (ascending) Stream<String> streamSorted = stream.sorted(); // 5. Display stream streamSorted // 5.1. Define an action that will display one stream item. // For this, the Consumer<T> interface is used. Consumer<String> action = (str) -> { System.out.println(str); }; // 5.2. Display each element of the stream streamSorted.forEach(action); // 6. Sort stream elements in descending order // 6.1. Implement a comparator - a method that compares two strings Comparator<String> comparator; comparator = (str1, str2) -> { return str2.compareTo(str1); // <0, ==0, >0 }; // 6.2. Create the new stream stream = AL.stream(); // 6.3. Sort stream Stream<String> streamSortedDesc = stream.sorted(comparator); // 6.4. Display new stream System.out.println("-----------------------"); streamSortedDesc.forEach(action); } }
The result of the program
abcd afc ambn bcfk def jklmn jprst jus kmk rbd ----------------------- rbd kmk jus jprst jklmn def bcfk ambn afc abcd
⇑
Related topics
- Examples of solving tasks on data streams, which are objects of the developed classes
- Data streams. Stream API. General information
⇑