1z0-809 Oracle Java SE 8 Programmer II – Java Stream API Part 2
January 27, 2023

4. 5.4 Develop code that uses Stream data methods and calculation methods

Hello everyone. In this lesson we will focus on the fourth item of the Java Stream API topic in the Java Sea Programmer two exam syllabus that is developing code that uses stream data methods and calculation methods. Stream data methods and calculation methods are basically reduction operations. This lesson covers six commonly used reduction operations, including count, min, max, reduce, average and sum. The Count method returns a long value representing the number of elements of the stream. The Min method returns an optional instance describing the minimum element of the stream. The Max method returns an optional instance describing the maximum element of the stream. The Reduce method performs a reduction operation on elements of the stream. The average method returns an optional double describing the arithmetic mean of elements of the stream or an empty optional if the stream is empty.

The sum method returns the total value of elements of the stream among all the methods shown here. These are defined in both the generic stream interface and its primitive type specializations, including instream, long stream and double stream. Meanwhile, these methods are declared only in primitive type specializations. Another reduction operation that’s worth mentioning is the collect method. You will learn about this method in a later lesson. Let’s get started with the Count method. This stream has three elements, so the Count method over here returns the number three, which is printed on the console. When this statement is executed. The signature and return type of the Count method are the same whether it is in the generic stream interface or in one of the primitive type specializations. Here is a code fragment demonstrating the Men and Max methods when they are invoked on a stream in a generic stream, these methods take a comparator argument as shown here and here. A stream in this example has five integer elements from one to five.

Therefore, the Min method returns an optional instance containing the number one, while the Max method returns an optional describing the number five. Note that the Min and Max methods in a primitive stream specialization don’t take any arguments as elements of such a stream can be ordered according to natural ordering. A reduced method performs a reduction operation on elements of the stream and returns an optional describing the reduced value or the reduced value itself depending on the overloaded version and use. The stream interface defines three reduce overloaded methods and two of them are introduced now. The third method, which has three parameters and are useful only when working on a parallel stream, will be covered later in another topic. The first reduce method we will go over is a method that has a single parameter of type binary operator.

This method performs a reduction on elements of the stream using the given associative accumulation function and returns an optional describing the reduced value. In this example, the accumulation operator adds up the value of two elements. As a result, the reduce method returns an optional object containing the sum of all stream elements which is 15 in this case. This statement prints out that sum on the console. Here is another overloaded version of the reduce method with two parameters an identity for the accumulator and the accumulator itself. This reduced method performs a reduction on elements of the stream using the provided identity value and the associative accumulation function and returns the reduced value. In this code snippet, the accumulator adds up stream integer elements with the identity zero like in the first example. The reduction result over here is also 15. Notice that instead of an optional, this reduce method returns a value of the same type as stream elements.

Similar to the generic stream interface, primitive stream interfaces have various versions of the reduce method with the parameter types and return type are primitive specializations of those of the methods you see here. The first thing you should take notice about the average and some methods is that they only work with primitive streams. There are no methods with such names. In the generic stream interface. The average method returns an optional double describing the arithmetic mean of elements of the stream or an empty optional if the stream is empty. In this example, the stream consists of six integer elements.

The average method here calculates the average value of those numbers which is 2. 5. This average value is wrapped in an optional double object then extracted in this statement. Notice that no matter the primitive stream is instream long stream or double stream, the return type of the average method is always optional double. The sum method returns the total value of elements of the stream. In this code fragment the sum of all stream elements is computed then printed on the console over here. The return value of the sum method is of the same type as stream elements. Now it’s time for some practice questions to go over what we have learned. Here is the first question. As always, feel free to pause the video if you need more time.

The Min and max methods calculate the minimum and maximum elements of a stream according to the provided comparator. There is nothing wrong with the code provided in this question and the string natural ordering determines that the letter B is greater than the letter A and is the maximum element of the stream. As a result, the correct answer is B. Now for the second question. This reduce method concatenates string elements of the given stream. When two elements are chained, the second element is put in front of the first one.

As such, this accumulator effectively reverses the order of elements and the reduction result is the string CBA. So the correct answer is B. Now for the third question. The reduce method with two parameters in the stream interface returns the reduced value rather than an optional object as shown here. Consequently, the given code fragment fails to be compiled and the correct answer is D. Notice that the identity value must be the identity for the accumulation function. The function in this case is multiplication.

So the identity should have been number one. When the accumulator identity is zero, even if the code were correct, the result would have always been zero, no matter how many elements are included in the stream. And option A would have been the correct answer. Now for the fourth question. The average method can only be invoked on a primitive type specialization of the stream interface. It cannot be called on a generic stream like this. This inappropriate invocation results in a compilation error. So the correct answer is C. In this lesson, we have gone over stream reduction methods. Let’s take a look at a summary. The count method returns a long value representing the number of elements of the stream. The Min and Max methods return the minimum and maximum elements of the stream respectively. The reduced method performs a reduction reduction operation on elements of the stream. The average method returns an optional double describing the arithmetic mean of elements of the stream. And the sum method returns the total value of elements of the stream.

5. 5.5 Sort a collection using Stream API

Hello everyone. In this lesson we will go over the fifth item of the JavaScript API topic and the JavaScript programmer two exam syllabus that is sorting a collection using Stream API. The Stream API defines combines two overloaded sorted methods that can be used for sorting elements of a stream. Among those methods, one has no parameters and the other has a parameter of type comparator. Both sorted methods are intermediate operations and are only executed when the terminal operation of the stream pipeline is initiated. The no argument sorted method of the stream interface returns a stream consisting of elements of the original stream. Elements of the returned stream are sorted according to their natural order. Since this method sorts elements based on natural ordering, the class of those elements must be a comparable implementation.

Otherwise, a class cast exception may be thrown. In this code example, the sorted method orders stream elements based on the natural ordering of the integer class. Therefore, regardless of the order of elements in the source collection, this consumer always prints numbers from the smallest to the biggest. The second overloaded sorted method has one parameter which is a comparator instance. This method returns a stream consisting of elements of the original stream sorted according to the given comparator. Here is a code fragment demonstrating the one parameter overloaded sorted method. Elements of this stream are sorted according to the provided comparator instead of their natural order. The comparator argument to method sorted in this scenario orders string elements in descending order. Therefore, this reduction operation returns an optional object describing a string concatenating stream elements in reverse alphabetical order. Now it’s time for some practice questions to go over what we have learned. Here is the first question.

As always, feel free to pause the video if you need more time. The no argument sorted method can only be invoked on a stream whose element type is a comparable implementation. The person class does not implement that interface despite its compare to method that has the same signature and return type as the only abstract method of the comparable interface. This issue, however, can only be found at runtime with a class Cast exception being thrown. Therefore, option C is the correct answer. If the person class implemented the comparable interface like this, option B would have been the correct answer. Now for the second question. When the sorted method is invoked with a comparator argument on a stream, the order of elements in the resulting stream is determined by that comparator ignoring the elements natural order in the given comparator.

Two person instances are compared based on the value of their name property. Since Adam goes before eva in alphabetical order, the correct answer is A. In this lesson, we have learned how to sort a collection using the Stream API. Here is a summary. The no argument sorted method of the stream interface returns a stream consisting of elements of the original stream sorted according to their natural order. The sorted method of the stream interface. That takes a comparator argument. Returns a stream containing elements of the original stream sorted according to the given comparator.

6. 5.6 Save results to a collection using the collect method and group/partition da

Hello everyone. In this lesson, we will go over the 6th item of the JavaScript API topic in the Java Se Eight programmer two exam syllabus that is saving results to a collection using the collect method and grouping and partitioning data using the collect class. An ordinary reduction on stream elements using the reduced method can collect data, but its performance might not be good as a new instance of the result type is created each time an element is handled.

For instance, if you wanted to concatenate a stream of strings into a single string using the reduce operation, the whole process would get involved with a great deal of string copying, which might result in deteriorated performance. Immutable reduction operation accumulates input elements into a mutable result container, such as a collection or string builder as it processes elements of the stream. Mutable reduction can be achieved using the collect method of the Stream API. A collect operation requires three functions a supplier function to construct new instances of the result container, an accumulation function to incorporate input elements into a result container, and a combination function to merge the contents from different result containers in a parallel stream.

Separate functions of a collect method are tightly coupled and can be replaced by a collector. This parameter captures all aspects of the collect operation, including supplier, accumulator and combiner writing. A class that implements the collector interface to work with the collect operation is complicated. However, the JDK Eight already provides you with a number of collector implementations out of the box, so you don’t need to read to that tricky job.

Collector instances can be created using predefined factory methods declared in the collector’s class. In this lesson, we will go through six of those static factory methods, including To List, To Set, To Collection, to map, grouping by, and partitioning by. In the collectors class, the Tolist method returns a collector instance that accumulates input elements into a new list, while To Set returns a collector accruing elements into a new set. Here is a code fragment that illustrates the To List and To Set methods. This To List method creates a collector that accumulates stream elements into a new list.

As a result, all of the elements are included in that list and printed out on the console. On the other hand, a set consists of distinct elements only, so a collector returned from the To set method filters out duplicate elements of the stream. If you want to have more control over the result container, you can use the to collection method. This method returns a collector that accumulates input elements into a new collection. In encounter order with two collection, you can specify a supplier that creates a new empty collection of the appropriate type, rather than relying on the list or set instance constructed by the runtime environment, as in the case of the To List or To Set method. In this example, this supplier argument indicates that a new instance of the linked list class must be created to store elements of the given stream.

The two map method of the collector’s class returns a collector that accumulates elements into a map whose keys and values are the result of applying the provided mapping functions to the input elements. Here is the signature of the to map method. This key mapper function produces the keys for the result map from stream elements, while value mapper creates map values. In fact, the collectors class contains two other overloaded methods of to map, but those versions are related to merge functions which are unlikely to appear in the exam. This is an example class to illustrate the two map method. The person class shown here has two properties ID and name. ID will be used as the map key and name as the map value. Here is a code fragment that makes use of the two map method. First, a stream of person is created. Its elements are then collected into a map using this to map method. The Gitid method of class person is the key mapper function, while Git name is the value mapper. Consequently, the result map contains entries whose key and value are properties of a person instance. The content of that map is printed here which is corresponding to the input elements of the stream.

The one parameter grouping by method of the collector’s class returns a collector implementing a group by operation on input elements, grouping them according to a classification function and returning the results in a map. The keys of the result map are created by applying the classification function to the input elements, and the corresponding values are list instances containing input elements that are mapped to the associated key by the classifier.

The two parameter grouping by method of the collector’s class returns a collector implementing a cascaded group by operation on input elements, grouping them according to a classification function, and then performing a reduction operation on the values associated with a given key using a downstream collector. This grouping by method has an overloaded version that accepts three parameters. In addition to the two parameters this method has. The three parameter version has a supplier parameter that constructs a map containing the result of the collect operation. You can find more information about that particular method in the Java API documentation. Here is a class to illustrate the grouping by method.

Pay attention to this Getter method because it will be used as the classification function in the next example. That Git gender returns an instance of the enum type gender whose declaration is shown here. In this example, both the streams stream one and stream two are created from these four person instances on the first stream.

This collect method groups elements by gender. The result of this group operation is a map whose keys are possible values returned from the specifier male and female. The value associated with each key is a list containing elements which are mapped to the corresponding key by the specification function regarding the second stream. In addition to what the first collect operation does, the collect method over here performs a reduction operation using a downstream collector. In this case, the collector calculates the average age of all persons in the same group. The result is put into a map and printed on the console like this. The one parameter partitioning by method of the collector’s class returns a collector partitioning input elements according to the given predicate and organizing them in a map with two entries.

The keys of these entries are true and false, and the values are list instances containing input elements on which the specified predicate evaluates to the value of the associated key. The two parameter partitioning by method of the collector’s class returns a collector partitioning input elements according to the given predicate, reducing the values in each partition based on another collector and organizing them into a map. The keys of the result map are true and false, and the corresponding values are produced by the reduction implemented by the downstream collector that operates on elements associated with each key. Here is a custom class used in the following example that demonstrates the partitioning by method. This is male method will be used as the predicate argument to that partition method in this example. Again, both stream one and stream two are created from four person instances. The collect method over here partitions elements of the first stream based on this Boolean valued function. The result of that operation is a map whose keys are Boolean values true and false. The value associated with the false key is a list containing persons whose gender is female, and the value corresponding to the true key is another list of persons whose gender is male. The content of the result map is shown over here.

As to the second stream, this collect method performs a reduction operation using a downstream collector. In this case, the collector calculates the average age of all persons in the same group. The result is put into a map and printed on the console like this now it’s time for some practice questions to go over what we have learned. Here is the first question. As always, feel free to pause the video if you need more time. The two collection method of the collector’s class has a parameter that is a supplier providing collection instances.

In the given scenario. No arguments are passed in resulting in a compilation error. As a result, the correct answer is D. If a valid argument were passed to the to collection method like this, option B would have been the correct answer. If a set supplier were provided instead of list, then option A would have been the correct answer. Now for the second question. The first function argument to the two map method is a key mapper, while the second is a value mapper. The return types of those mappers do not match the key and value types of the result map. This mismatch leads to a compilation error, so the correct answer is D. If type arguments to the result map were changed this way, option A would have been the correct answer.

You could also switch the position of function arguments to the two map method like this. In this case, option B would have been the correct answer. Now for the third question. The second argument to the two parameter grouping by method of the collector’s class must be a collector, not a function. The passing of this invalid argument results in a compilation error, so the correct answer is C. Now for the fourth question. The given code fragment is completely valid, so there are no compilation errors. The partitioning by method of the collector’s class returns a collector partitioning input elements according to the given predicate and organizing them into a map.

This map has two entries with keys false and true. The value associated with each of those keys is a list of persons matching the return value of the predicate. So the correct answer is B. In this lesson, we have gone over mutable reduction operations on a stream using the collect method of the stream API along with factory methods defined in the collector’s class. To sum up, a mutable reduction operation accumulates input elements into a mutable result container as it processes elements of the stream. The collect method performs a mutable reduction operation on elements of the stream. This method requires three functions which may be passed separately or wrapped in a collector. The collector’s class provides a number of predefined static factory methods to create collectors, including to list, to set, to collection, to map grouping by, and partitioning by.

7. 5.7 Use flatMap() methods in the Stream API

Hello everyone. In this lesson we will cover the last item of the Java Stream API topic and the JavaScript Programmer two exam syllabus that is using flatmap methods. In the Stream API, the Flatmap method returns a stream consisting of the results of replacing each element of the original stream with the contents of a mapped stream produced by applying the provided mapping function to that element. Those mapped streams are closed after their contents have been processed. If the mapping function produces a null value, such a value is replaced by an empty stream. The Flat Map operation basically implements a one to many transformation on different streams of the same type. Flattening all elements of individual input streams into a single stream. Here is the signature of the Flat Map method. This mapping function transforms elements of input streams into a new one.

The return type of this method is stream, meaning that it is an intermediate operation. Primitive type specializations of the Flat Map method have the same functionality as that method, except they work with primitive streams. The name of primitive specializations is similar to the Flat Map method except for the suffix denoting their supported primitive type like this, this and this. Each of these methods returns a primitive stream instead of a generic one. Here are two classes to illustrate the Flat Map method and its primitive type specializations.

The course class has a one to many relationship with the student class. In the example that follows, elements in streams of student will be flattened when the Flat Map method operates on a stream. Of course. In the example over here, first four student instances and two course objects are created. Students are then added to courses. In this statement, a collection is constructed from those course instances. Next, the Flat Map method is invoked on the stream created from that collection extracting all student elements in the streams mapped from input courses. The result of this Flat Map operation is a stream of students. This, for each operation outputs the name of all students on the console. This is a primitive type specialization of the Flat Map method. Rather than returning a stream of an object reference type, the function argument to this method returns a primitive stream. This return type determines the output stream of the Flat Map operation, which is also a primitive stream. Here are the contents of the output stream, in this case printed by this terminal operation. Now it’s time for some practice questions to go over what we have learned. Here is the first question. As always, feel free to pause the video if you need more time.

When the mapping function over here operates on this state element, the mapped stream generated from it is empty. Such an empty input stream is completely valid in the Flat Map operation, so no compile time or runtime errors occur. The output of this method is therefore a stream containing cities taken from the state of Texas as such, the correct answer is A. Now for the second question. This stream is closed after its contents are placed into the stream returned from the Flat Map operation over here. Consequently, the next time an operation is initiated on that stream, an illegal state exception will be thrown. Before that point, the only element of the double stream generated from this student instance is flattened and printed on the console. Therefore, the correct answer is B. In this lesson, we have gone over how to use flatmap methods in the stream API. To summarize, the Flat Map method returns a stream consisting of the results of replacing each element of the original stream with the contents of a mapped stream produced by applying the provided mapping function to that element. The Flat map method has three primitive type specializations with the same functionality, including flat map to int, flat map to long and flat map to double.

Leave a Reply

How It Works

img
Step 1. Choose Exam
on ExamLabs
Download IT Exams Questions & Answers
img
Step 2. Open Exam with
Avanset Exam Simulator
Press here to download VCE Exam Simulator that simulates real exam environment
img
Step 3. Study
& Pass
IT Exams Anywhere, Anytime!