Loading topic
Optional, you need to see the problem it solves. This chapter covers what null is, why it causes so many crashes, and why programmers wanted a better way to say "there might be no value here."6 min readnull causes trouble. A method can return null to mean "nothing here." The caller can easily forget to check for it. Then the program crashes with a NullPointerException.6 min readOptional, a box that either holds one value or holds nothing. Before you can use that box, you need to make one. This chapter shows the three ways to do that and how to pick the right one.5 min readisPresent and isEmpty.6 min readget, orElse, orElseGet, and orElseThrow. Each one handles the empty case differently. By the end, you will know which method to use and why get is usually the wrong pick.5 min readOptional with a fallback: orElse and orElseGet. They look almost the same, and most of the time they return the same result. They differ in when the default value is made. This chapter shows that difference, explains why it can matter, and5 min readOptional safely. Often, though, you don't want the value exactly as it is. You might want to trim it, change it to uppercase, or turn a name into its length. Sometimes you only want to keep the value if it passes a test.5 min readmap to change the value inside an Optional. That works well when your function returns a plain value, such as a String or an int. Sometimes, though, the function you want to call already returns an Optional. Then map gives you an awkward result: an Optional insid5 min read.stream() on a collection like a List. Some stream steps end with a single answer, for example "the first name that starts with B" or "the cheapest product." The list5 min readOptional<T>, where T is a class such as String or Customer. Java also has three smaller cousins built for plain numbers: OptionalInt, OptionalLong, and OptionalDouble. This chapter explains what they are, why they exist, and how to use them without surprises.5 min readOptional. The or method lets you try a backup source when a value is missing. The stream method turns an Optional into a stream so it fits into stream pipelines. This chapter covers both methods, shows how each behaves, and points out the mistakes beginners6 min readOptional offers. This last chapter covers when to use those tools and when to leave them alone. Optional works well in some places and makes code worse in others.5 min read