1. 5.1 Develop code to extract data from an object using peek() and map() methods i
Hello everyone. In this lesson we will focus on the first item of the Java Stream API topic in the Javas Eight programmer two exam syllabus that is developing code to extract data from an object using Peak and Map methods, including primitive versions of the Map method. The Peak method of interface stream performs an action on each element of the stream. This is the signature of the Peak method. Its action argument is a consumer. The method returns a stream containing elements of the original one. Since the return value of this method is a stream, it is an intermediate operation and the given action is only executed when the resulting stream is consumed. This Peak method works via side effects and is usually used for logging. Here is the class that will be used to illustrate the Peak and Map methods in the following examples. This class named Person has two properties name and Age. Name is a string, while age is an in value. This is an example demonstrating the Peak method. First, two person instances are created and used to construct a stream of person. Property.
Values of the stream elements are printed on the console by this action, which is a consumer passed to the Peak method. Notice that Peak is an intermediate operation, so its action does not do anything until a terminal operation is initiated on the resulting stream. The for each method over here does nothing but trigger stream operations. The Map method of interface stream applies a mapper to elements of the stream. This is the signature of the Map method. Its Mapper argument is a function instance. The method returns a stream consisting of the results of the given function.
Like the Peak method, this Map method is also an intermediate operation, so the given mapper only takes action when the resulting stream is consumed. This is an example on the Map method. A person stream is created over here. Then its elements are mapped to a stream of string using this function. The mapping is executed when the resulting stream is consumed like this. The Map operation of the stream interface has three primitive type specializations including Map to Int, Map to Long and Map to Double. Each of these methods takes a primitive version of function as its argument and returns a primitive specialization of stream. Here are signatures of those primitive specializations. Each method is named Map Two followed by a suffix implying the type of the resulting stream.
The argument to such a method is also a primitive type specialization of the generic function interface. This is an example demonstrating a primitive Map method. These statements create a stream of person. Elements of the stream are then mapped to an int primitive stream by this primitive function. Finally, those mapped elements are output on the console 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. This action argument to the Peak method prints the uppercase version of all string elements of this stream. The passing is completely valid, so there are no errors and the correct answer is B. Now for the second question. This Map method is an intermediate operation. Therefore, without a terminal operation, the function argument to the Map method is not executed and nothing is printed out. So the correct answer is C.
Now for the third question. The argument to this Map to double method must be an instance of the two double function interface, not double function. This type mismatch leads to a compilation error, so the correct answer is D. In this lesson, we have gone over the Peak and Map methods of the stream interface. Here is a quick summary. The Peak method of interface stream performs an action on each element of the stream. The Map method of interface stream applies a mapper to elements of the stream. This method has three primitive type specializations including Map to Int, Map to Long and Map to Double. The Peak and Map methods as well as all primitive type specializations of Map are intermediate operations.
2. 5.2 Search for data by using search methods of the Stream classes including find
Hello everyone. In this lesson, we will go over the second item of the Java Stream API topic and the JavaScript Programmer II exam syllabus that is searching for data by using search methods of the stream classes including Find First, Find Any, Any Match, All Match, and None Match. You can search for data in a stream using the following two kinds of methods starting with Find, these methods return an optional instance describing an element of the stream. There are two methods of this kind, namely Find First and Find Any methods ending with Match. These methods return whether elements of the stream match the given predicate. Three methods of this kind are any match, all match and none match. All of these methods will be covered shortly. The Find First method is a short circuiting terminal operation returning an optional object that describes the first element of the stream, or an empty optional if the stream is empty. Here is the signature of the Find First method. This method does not have any parameters. If the stream has no encounter order, any element may be returned. The Find Any method is a short circuiting terminal operation returning an optional object that describes an arbitrary element of the stream, or an Empty optional if the stream is empty.
This is the signature of the Find Any method. Like the Find First method, this one does not have any parameters. The behavior of Find Any is non deterministic, and it may select any element in the stream. This behavior allows for maximal performance in parallel operations. On the flip side, however, multiple invocations on the same source may not return the same result. If you need a consistent outcome, you should use the Find First method instead. Here is the class that will be used to illustrate search methods of the stream interface and the examples that follow. This class named Person has two properties name and Age. Name is a string, while Age is an int value.
This is an example demonstrating the Find First and Find Any Methods first two person instances are created and used to construct a stream of person. The Find First method always picks up the first element, so this statement always prints Dylan 30 on the console. On the other hand, the Find Any method returns a random element. Therefore, when this print line statement is executed, property values of either element are output. Now, let’s move on to the second kind of search methods. The Any Match method is a short circuiting terminal operation returning Whether any elements of the stream match the given predicate. If the stream is empty, then false is returned and the predicate is not evaluated. This is the signature of the Any Match method.
Notice that the predicate argument may not be evaluated on all elements of the stream. If that is not necessary to determine the result. The All Match method is a short-circuiting terminal operation, returning whether all elements of the stream match the given predicate. If the stream is empty, then True is returned and the predicate is not evaluated. This is the signature of the All Match method. Like in the Any Match method, the predicate argument may not be evaluated on all elements of the stream. If that is not necessary to determine the result, the Non Match method is a shortcircuiting terminal operation, returning whether no elements of the stream match the given predicate. If the stream is empty, then True is returned and the predicate is not evaluated. This is the signature of the Non Match method. Like in the case of Any Match and All Match, this predicate argument may not be evaluated on all stream elements. Here is an example illustrating the operations of methods. Any match? All match and none match. This predicate evaluates to true for Dylan and false for Sarah. Since there is at least one element that matches the provided predicate, any Match returns True and None Match returns False. Meanwhile, since at least one element does not match the given predicate, the All Match method also returns false. Now, it’s time for some practice questions to go over what we have learned. Here is the first question. As always, if you need more time, feel free to pause the video.
This findfirst method returns an optional instance, allowing you to extract a stream element from it. The method does not directly return an object of the stream element type like this. As a result, this statement fails to be compiled and the correct answer is D. Now for the second question. As per the Java Eight API documentation, the behavior of the Find Any method is explicitly non deterministic. It is free to select any element in the stream. This is to allow for maximal performance in parallel operations. The cost is that multiple invocations on the same source may not return the same result. Based on that documentation, it is clear that the correct answer is C.
Now for the third question when a stream is empty, the All Match method immediately returns True and the predicate argument is not evaluated at all. As a result, the correct answer is A. Now for the fourth question. This predicate evaluates to True for all elements of the stream. As such, both the all match and any match methods return true whereas the non match method returns false. So the correct answer is C. In this lesson, we have gone over search methods of the stream interface. Let’s take a look at a summary of the lesson. The Find first method returns an optional describing the first element of the stream. The Find Any method returns an optional describing an arbitrary element of the stream. The Any Match method returns whether any elements of the stream match the given predicate. The All Match method returns whether all elements of the stream match the given predicate. The Non Match method returns whether no elements of the stream match the given predicate.
3. 5.3 Develop code that uses the Optional class
Hello everyone. In this lesson, we will go through the third item of the Javastream API topic and the JavaScript programmer two exam syllabus that is developing code that uses the optional class. Prior to the introduction of the optional class, Java developers have long suffered a pain called null reference. This kind of reference was invented in 65 by computer scientist Tony HoR, which refers to a reference variable that does not point to any object in the memory. Tony later called null reference, his billion dollar mistake that has led to innumerable errors, vulnerabilities, and system crashes. Let’s see what the problem with null references really is and how the optional class helps to fix that. Here are example classes that do not use optional. The person class has a property named address which is of type address. This is the declaration of the address class. It has a property named street.
These are a couple of statements using the classes you have just seen. In this case, the address property of person is not set. So this expression evaluates to null accessing a property from a null reference like this results in a null pointer exception. You can avoid the null pointer exception by using a null check as shown here. However, this kind of check leads to convoluted code with functional and nonfunctional statements blended. This makes the code less readable and harder to maintain. The problem with null references can be solved in a better way with the help of the optional class. Instead of the address type, the address property is now declared with the optional type, and the address class is used as the type argument to that type. In addition, rather than leaving the address property uninitialized, we assign it an empty optional, which is an optional object without a value. You can extract the value enclosed in an optional object using its simplest retrieval method, Git.
When the address property of person is not set, this Git method throws a no such element exception because the initial value of that property is an empty optional instance. You can avert the exception using the Is present method defined in the optional class. This method checks if a value is present in an optional instance. At this point, you may wonder what benefits the optional class brings in. Instead of null pointer exception, a no such element exception might be thrown. We have also got rid of null checks, but ended up with using the is present method. This does not look like an improvement. In fact, the git method is not the only way to retrieve the value in an optional class. You should only use it when that object is guaranteed to be none empty. The optional class comes with many useful methods you can use to make your code more organized and readable. Those methods will be introduced now. The optional class does not have public constructors. You can therefore only create its instances using public static methods. The empty method returns an empty optional instance. This means that the returned optional contains no value.
The empty method does not take any arguments. As shown here, the of method returns an optional instance with the given value if it is nonnull, otherwise a null pointer exception is thrown. Here is an example demonstrating the of method. In the first statement, the argument of method of is a string, so this object contains a value which is the given string. In the second statement, a null value is passed to the of method. This passing causes a null pointer exception to be thrown. The Ofnullable method returns an optional instance with the given value if it is non null, otherwise returns an empty optional. This method is safer than method of, and you can use it to create an optional object without worrying about the null pointer exception. When the argument to Annullable is non null, it behaves the same way as the of method. The difference appears when a null value is passed in.
Instead of throwing an exception, the of nullable method creates an empty optional object. Now let’s move on to methods that retrieve the value contained in an optional object. The git method returns the value contained in the optional object if it is present. If the optional is empty, this method throws a no such element exception. In this code fragment, variable op wizlabs references an optional object that has a string value. This value is printed on the console when this statement is executed. On the other hand, variable opmpt references an empty optional and the invocation of the git method over here throws an exception. The or else method returns the contained value if it is present, otherwise it returns the given argument. This method behaves the same way as the get method if the optional object contains a value, ignoring the argument. If the object is empty rather than throwing an exception, the or else method returns its argument. The or else Git method returns the contained value if it is present. Otherwise, it invokes the supplier argument and returns the invocation result. This code fragment should help you better understand the or else Git method. If the optional object is not empty, it returns the same value as the git or or else method. If the object is empty, like in this case, the supplier argument to this method is executed and or else get returns the result of this supplier. The or else throw method returns the contained value if it is present. Otherwise it throws an exception created by the supplier argument. You can see an example of this method over here. However, the or else throw method is rarely used and included in this lesson. Just for the sake of completeness. The is present method returns true if there is a value present, otherwise it returns false. Here is a code fragment that makes use of the is present method. If an optional object is not empty, the is present method invoked on that optional returns true if the optional object is empty is present. Returns false the if present method invokes the consumer argument if the value is present. Otherwise it does nothing.
In this code fragment, the print line statement over here is executed and it prints the value contained in the optional object. When an object is empty, the same statement does nothing. The filter method returns an optional object describing the value if it is present and matches the predicate argument. Otherwise it returns an empty optional. In this code example, the op integer variable references an optional object whose value is number one. This number does not satisfy the given predicate, so the op filtered variable points to an empty optional object. This is the reason why the statement over here prints false on the console. The map method applies the mapping function argument to the value if it is present and if the result is nonnull, returns an optional describing the result. Otherwise this method returns an empty optional. Here is an example illustrating the map method of optional. This function transforms the string value contained in the current optional object to an integer which denotes the length of the string. The map method then returns an optional object describing that length value. The wizlabs string has eight characters, so this statement outputs the number eight. The flat map method applies the optional bearing mapping function argument to the value if it is present, then returns an optional describing the result.
Otherwise, this method returns an empty optional. Flat map is usually used in the place of the map method if the return type of the given function is optional. This is a code fragment demonstrating the flat map method. The difference between this method and the map method is the return type of the input function is already optional, and the return value of that function is returned directly to the caller. Meanwhile, the map method wraps the return value of its function argument in an optional before returning. 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. This stream does not contain any elements, so the find any method here returns an empty optional instance. As you have learned, the Git method throws a no such element exception when it is invoked on an empty optional. So the correct answer to this question is b and D.
Now for the second question. The stream over here has only one element, number zero. This method then returns an optional object describing that single element of the stream. The value of that optional satisfies this predicate, so the filter method returns an optional containing the number zero. This optional is not empty, so the or else get method returns the enclosed value or the number zero and ignores the given supplier. Such a value is printed when the print line statement over here is executed. As a result, option A it prints the number zero is the correct answer. Now for the third question. This optional object is empty, so the map method over here returns an empty optional. The git method throws a no such element exception when it is invoked on an empty optional object. As a result, option C it throws an exception is the correct answer. Now for the fourth question. The argument to the flat map method must be a function that returns an optional object, not a string. For this reason, the given code fails to be compiled, so the correct answer is D. In this lesson, we have gone over how to develop code that uses the optional class. Here is a summary. The optional class is usually used to avoid null references. This class defines three creation methods empty, of, and of nullable. You can retrieve the value in an optional object using one of the methods get or else, or else get and or else throw. You can check an optional instance for emptiness using the is present method. The optional class also defines several methods that work with a functional interface argument. They are, if present, filter, map, and flatmap.