Calculator Show and Tell
Screenshots?
An Aperitif: Optional<T>
This is the Schrödinger's Cat of objects. Let us learn about it. It will appear a lot when we study the Streams API and it is also useful in a variety of other contexts.
jshell> Optional<String> s = Optional.empty();
s ==> Optional.empty
jshell> s
s ==> Optional.empty
jshell> s.isEmpty()
$3 ==> true
jshell> //m
No such command
jshell> //make an Optional<String> with "cat" in it.
jshell> s.isPresent()
$4 ==> false
jshell> s = new Optional<>();
| Error:
| cannot infer type arguments for java.util.Optional<>
| reason: cannot infer type-variable(s) T
| (actual and formal argument lists differ in length)
| s = new Optional<>();
| ^--------------^
jshell> s.getClass()
$5 ==> class java.util.Optional
jshell> s = Optional.of("cat")
s ==> Optional[cat]
jshell> s.orElse("cow")
$7 ==> "cat"
jshell> Optional t = Optional.empty();
t ==> Optional.empty
jshell> t.orElse("cow")
| Warning:
| unchecked call to orElse(T) as a member of the raw type java.util.Optional
| t.orElse("cow")
| ^-------------^
$9 ==> "cow"
jshell> s
s ==> Optional[cat]
jshell> String pet = s.get()
pet ==> "cat"
jshell> s.toString()
$12 ==> "Optional[cat]"V
The Streams API
There are three components.
- A source
- Zero or more transformations
- A terminal operation
Streams are lazy; they do nothing until a terminal operaton tells them to.
Once a stream is consumed, you have to make a new one.
A string will give you an IntStream of its characters A Collection will give you a stream of its elements An Array will give you a stream of its elements using the static method Arrays.stream(). A buffered reader will give you a stream of strings using lines()
How do you get a Stream from an ArrayList?
How do you get a Stream from a lowly array?
How do you get a Stream from a file?