Title: Java 8 Optional Example - Java Code Geeks
Open Graph Title: Java 8 Optional Example - Java Code Geeks
Description: In this article, we are going to show how to use the new Java 8 Optional - java.util.Optional class. 1. Introduction The null reference is a very common
Open Graph Description: In this article, we are going to show how to use the new Java 8 Optional - java.util.Optional class. 1. Introduction The null reference is a very common
Mail addresses
support@javacodegeeks.com
Opengraph URL: https://examples.javacodegeeks.com/java-8-optional-example/
Generator: WordPress 6.9.4
Domain: examples.javacodegeeks.com
{"@context":"https://schema.org","@graph":[{"@type":"Article","@id":"https://examples.javacodegeeks.com/java-8-optional-example/#article","isPartOf":{"@id":"https://examples.javacodegeeks.com/java-8-optional-example/"},"author":{"name":"Dani Buiza","@id":"https://examples.javacodegeeks.com/#/schema/person/ee0f431dd55475919f56a8b41e52b219"},"headline":"Java 8 Optional Example","datePublished":"2014-08-07T08:00:22+00:00","dateModified":"2020-07-23T09:00:48+00:00","mainEntityOfPage":{"@id":"https://examples.javacodegeeks.com/java-8-optional-example/"},"wordCount":1795,"commentCount":0,"publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"image":{"@id":"https://examples.javacodegeeks.com/java-8-optional-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","articleSection":["Optional"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https://examples.javacodegeeks.com/java-8-optional-example/#respond"]}]},{"@type":"WebPage","@id":"https://examples.javacodegeeks.com/java-8-optional-example/","url":"https://examples.javacodegeeks.com/java-8-optional-example/","name":"Java 8 Optional Example - Java Code Geeks","isPartOf":{"@id":"https://examples.javacodegeeks.com/#website"},"primaryImageOfPage":{"@id":"https://examples.javacodegeeks.com/java-8-optional-example/#primaryimage"},"image":{"@id":"https://examples.javacodegeeks.com/java-8-optional-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","datePublished":"2014-08-07T08:00:22+00:00","dateModified":"2020-07-23T09:00:48+00:00","description":"In this article, we are going to show how to use the new Java 8 Optional - java.util.Optional class. 1. Introduction The null reference is a very common","breadcrumb":{"@id":"https://examples.javacodegeeks.com/java-8-optional-example/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https://examples.javacodegeeks.com/java-8-optional-example/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/java-8-optional-example/#primaryimage","url":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https://examples.javacodegeeks.com/java-8-optional-example/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://examples.javacodegeeks.com/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https://examples.javacodegeeks.com/category/java-development/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https://examples.javacodegeeks.com/category/java-development/core-java/"},{"@type":"ListItem","position":4,"name":"util","item":"https://examples.javacodegeeks.com/category/java-development/core-java/util/"},{"@type":"ListItem","position":5,"name":"Optional","item":"https://examples.javacodegeeks.com/category/java-development/core-java/util/optional/"},{"@type":"ListItem","position":6,"name":"Java 8 Optional Example"}]},{"@type":"WebSite","@id":"https://examples.javacodegeeks.com/#website","url":"https://examples.javacodegeeks.com/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://examples.javacodegeeks.com/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https://examples.javacodegeeks.com/#organization","name":"Exelixis Media P.C.","url":"https://examples.javacodegeeks.com/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/logo/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https://examples.javacodegeeks.com/#/schema/logo/image/"},"sameAs":["https://www.facebook.com/javacodegeeks","https://x.com/javacodegeeks"]},{"@type":"Person","@id":"https://examples.javacodegeeks.com/#/schema/person/ee0f431dd55475919f56a8b41e52b219","name":"Dani Buiza","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/person/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2014/06/Dani-Buiza-96x96.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2014/06/Dani-Buiza-96x96.jpg","caption":"Dani Buiza"},"description":"Daniel Gutierrez Diez holds a Master in Computer Science Engineering from the University of Oviedo (Spain) and a Post Grade as Specialist in Foreign Trade from the UNED (Spain). Daniel has been working for different clients and companies in several Java projects as programmer, designer, trainer, consultant and technical lead.","sameAs":["http://danibuiza.github.io/yo/"],"url":"https://examples.javacodegeeks.com/author/dani-buiza/"}]}
{"@context":"http:\/\/schema.org","@type":"BreadcrumbList","@id":"#Breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"item":{"name":"Home","@id":"https:\/\/examples.javacodegeeks.com\/"}},{"@type":"ListItem","position":2,"item":{"name":"Java Development","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"}},{"@type":"ListItem","position":3,"item":{"name":"Core Java","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"}},{"@type":"ListItem","position":4,"item":{"name":"util","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/util\/"}},{"@type":"ListItem","position":5,"item":{"name":"Optional","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/util\/optional\/"}}]}
{"@context":"http:\/\/schema.org","@type":"Article","dateCreated":"2014-08-07T11:00:22+03:00","datePublished":"2014-08-07T11:00:22+03:00","dateModified":"2020-07-23T12:00:48+03:00","headline":"Java 8 Optional Example","name":"Java 8 Optional Example","keywords":[],"url":"https:\/\/examples.javacodegeeks.com\/java-8-optional-example\/","description":"In this article, we are going to show how to use the new Java 8 Optional - java.util.Optional class. 1. Introduction The null reference is a very common problem in Java, everybody got once a NullPoint","copyrightYear":"2014","articleSection":"Optional","articleBody":"\nIn this article, we are going to show how to use the new Java 8 Optional - java.util.Optional class.\n\n\n\n1. Introduction\n\n\n\nThe null reference is a very common problem in Java, everybody got once a NullPointerException because some variable or input parameter was not properly validated. In Java, null, can have a logical value and a meaning; so it is important to take it into consideration and do not ignore it.\n\n\n\nWith the introduction of java.util.Optional in Java 8, several new possibilities for handling this problematic are available.\n\n\n\nThe new class is based on the analog functionalities in Haskell and Scala. It contains a value that can be present or not; if the value is not present, the Optional instance is said to be empty.\n\n\n\nAll examples and code snippets listed have been done using Eclipse Luna version 4.4 and Java version 8 update 5 and can be downloaded at the end of this article.\n\n\n\n2. Java 8 Optional\n\n\n\nempty() - Returns an empty Optional instance.\n\n\n\nIn order to create a Java 8 Optional we have to indicate what type of value is going to contain:\n\n\n\n\n\n\n\n\n\n1\n\n\n\nOptional emptyOptional = Optional.empty();\n\n\n\n\n\n\n\n\n\n\nThe code above shows the creation of an empty optional, that is, its value is null or not initialized.\n\n\n\nget() - If a value is present, returns the value, otherwise throws NoSuchElementException.\n\n\n\nIn order to access the value of an optional we can use the method get(); if we try to access the value of the example shown above, we would get the following exception.\n\n\n\n\n\n\n\n\n\n01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n\n\n\ntry\n{\n \/* empty *\/\n Optional emptyOptional = Optional.empty();\n System.out.println( emptyOptional.get() );\n}\ncatch( NoSuchElementException ex )\n{\n System.out.println( \"expected NoSuchElementException\" ); \/\/this is executed\n}\n\n\n\n\n\n\n\n\n\n\nThe exception thrown is of the type java.util.NoSuchElementException and means that the Optional value is not initialized or null.\n\n\n\nof() - Returns an Optional describing the given non-null value.\n\n\n\nIn order to create a Java 8 Optional, we can use an existing object and pass it to the Optional using the static method of():\n\n\n\n\n\n\n\n\n\n1\n\n\n\nOptional nonEmptyOptional = Optional.of( str ); \n\n\n\n\n\n\n\n\n\n\nThe object passed to the method of() has to be different to null.\n\n\n\nofNullable() - Returns an Optional describing the given value, if non-null, otherwise returns an empty Optional.\n\n\n\nIn case we want to offer the possibility of using potential null values, we can use ofNullable():\n\n\n\n\n\n\n\n\n\n1\n2\n\n\n\nString strNull = null;\nOptional nullableOptional = Optional.ofNullable( strNull );\n\n\n\n\n\n\n\n\n\n\nIf we try to pass a null object to a Java 8 Optional using the method of() we will get a NullPointerException. At the end of this article there is a file to download with examples of all these possible combinations. In order to get the value of an Optional you can use the get() method as shown above. The problem of this method is that you can get a NullPointerException if the value is not initialized. So, although it has some benefits is not solving all our problems.\n\n\n\nThere are several methods that can be used to retrieve the value of an Optional and handle at the same time the possibility that it is a null reference. We are going to see some of them:\n\n\n\norElse() - If a value is present, returns the value, otherwise returns other.\n\n\n\nWe can use the method orElse():\n\n\n\n\n\n\n\n\n\n1\n2\n\n\n\nOptional optionalCar = Optional.empty();\nprice = optionalCar.orElse( defaultCar ).getPrice();\n\n\n\n\n\n\n\n\n\n\nIn the code shown above we are trying to access to the price of a Car object, if the Car object is not initialize (or it is null) we will retrieve the price for the default car that we have defined before.\n\n\n\norElseGet() - If a value is present, returns the value, otherwise returns the result produced by the supplying function.\n\n\n\nThe difference between orElse and orElseGet is that orElse() will always call the given function whether you want it or not, regardless of Optional.isPresent() value while orElseGet() will only call the given function when the Optional.isPresent() == false.\n\n\n\nString n = Optional.of(\"Java\").orElseGet(() -> getRandomName()); \n\n\n\norElseThrow() - If a value is present, returns the value, otherwise throws NoSuchElementException.\n\n\n\nWe can indicate the Optional to throw an exception in case its value is null:\n\n\n\n\n\n\n\n\n\n1\n2\n\n\n\nOptional optionalCarNull = Optional.ofNullable( carNull );\noptionalCarNull.orElseThrow( IllegalStateException::new );\n\n\n\n\n\n\n\n\n\n\nIn this case, an IllegalStateException will be thrown.\n\n\n\norElseThrow(Supplier<? extends X> exceptionSupplier) - If a value is present, returns the value, otherwise throws an exception produced by the exception supplying function.\n\n\n\nThe difference between these two orElseThrow methods are the following:\n\n\n\nT - orElseThrow():\n\n\n\nReturns the non-null value described by this OptionalThrows NoSuchElementException - if no value is present\n\n\n\n<X extends Throwable> T - orElseThrow():\n\n\n\nReturns the value, if presentThrows X if no value is present and NullPointerException if no value is present and the exception supplying function is nullParameters: exceptionSupplier - the supplying function that produces an exception to be thrown\n\n\n\npublic T orElseThrow(Supplier exceptionSupplier) throws Throwable{\n\n throw exceptionSupplier.get();\n }\n\n\n\n\nor() - If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function. (added in java 9)\n\n\n\nThe difference between optional.or and optional.orElseGet is basically the return type but let's see all of them in detail:\n\n\n\nOptional.orElseGet():\n\n\n\nThe call to orElseGet returns the object T itself.throws NullPointerException if no value is present and the supplying function is nullUse case: To fetch the value deterministically based on the supplied function.\n\n\n\nOptional.or():\n\n\n\nThe Optional.or returns an Optional describing the value, otherwise returns an Optional produced by the supplying functionthrows NullPointerException if the supplying function is null or if the supplying function produces a null result.\n\n\n\nisPresent() - If a value is present, returns true, otherwise false.\n\n\n\nThere is the possibility to check directly if the value is initialized and not null:\n\n\n\n\n\n\n\n\n\n1\n2\n3\n4\n5\n\n\n\nOptional stringToUse = Optional.of( \"optional is there\" );\nif( stringToUse.isPresent() )\n{\n System.out.println( stringToUse.get() );\n} \n\n\n\n\n\n\n\n\n\n\nifPresent() - If a value is present, performs the given action with the value, otherwise does nothing.\n\n\n\nAnd also the option to execute actions directly when the value is present, in combination with Lambdas:\n\n\n\n\n\n\n\n\n\n1\n2\n\n\n\nOptional stringToUse = Optional.of( \"optional is there\" );\nstringToUse.ifPresent( System.out::println );\n\n\n\n\n\n\n\n\n\n\nThe code shown above and the one before are doing exactly the same. I would prefer to use the second one. So these are some of the available methods to retrieve the values of an Optional and to handle the null references.\n\n\n\nifPresentOrElse() - If a value is present, performs the given action with the value, otherwise performs the given empty-based action.\n\n\n\nSyntax:\n\n\n\nifPresentOrElse(action, emptyAction)\n\n\n\nParameters:action - the action to be performed, if a value is presentemptyAction - the empty-based action to be performed, if no value is present\n\n\n\nvalue.ifPresentOrElse(\n v -> successCount.incrAndGet(), \n EmptyOptCount::incrAndGet); \n\n\n\nNow we are going to see the options that are offered in combination with Lambdas:\n\n\n\nfilter() - If a value is present, and the value matches the given predicate, returns an Optional describing the value, otherwise returns an empty Optional.\n\n\n\nThe Optional class contains a filter() method that expects a Predicate and returns an Optional back if the Predicate is true. Here are some examples:\n\n\n\n\n\n\n\n\n\n01\n02\n03\n04\n05\n06\n07\n08\n09\n10\n11\n\n\n\n\/\/ if the value is not present\nOptional carOptionalEmpty = Optional.empty();\ncarOptionalEmpty.filter( x -> \"250\".equals( x.getPrice() ) ).ifPresent( x -> System.out.println( x.getPrice() + \" is ok!\" ) );\n \n\/\/ if the value does not pass the filter\nOptional carOptionalExpensive = Optional.of( new Car( \"3333\" ) );\ncarOptionalExpensive.filter( x -> \"250\".equals( x.getPrice() ) ).ifPresent( x -> System.out.println( x.getPrice() + \" is ok!\" ) );\n \n\/\/ if the value is present and does pass the filter\nOptional carOptionalOk = Optional.of( new Car( \"250\" ) );\ncarOptionalOk.filter( x -> \"250\".equals( x.getPrice() ) ).ifPresent( x -> System.out.println( x.getPrice() + \" is ok!\" ) );\n\n\n\n\n\n\n\n\n\n\nAs we can see in the snippet above we do not have to take care of the null reference of the value, we can just apply our filters directly and the Optional takes care of all the rest.\n\n\n\nmap\u00e2\u20ac\u2039() - If a value is present, returns an Optional describing (as if by ofNullable) the result of applying the given mapping function to the value, otherwise returns an empty Optional.\n\n\n\nIt is also very interesting the method map(). This method \"maps\" or converts an Optional to another Optional using a Function as parameter. The mapping is only executed, if the result of the past Function is not null. Here are some examples:\n\n\n\n\n\n\n\n\n\n1\n2\n3\n4\n5\n6\n7\n8\n9\n\n\n\n\/\/ non empty string map to its length -> we get the lenght as output (18)\nOptional stringOptional = Optional.of( \"loooooooong string\" );\nOptional sizeOptional = stringOptional.map( String::length ); \/\/map from Optional to Optional\nSystem.out.println( \"size of string \" + sizeOptional.orElse( 0 ) );\n \n\/\/ empty string map to its length -> we get 0 as lenght\nOptional stringOptionalNull = Optional.ofNullable( null );\nOptional sizeOptionalNull = stringOptionalNull.map( x -> x.length() ); \/\/ we can use Lambdas as we want\nSystem.out.println( \"size of string \" + sizeOptionalNull.orElse( 0 ) );\n\n\n\n\n\n\n\n\n\n\nflatMap() - If a value is present, returns the result of applying the given Optional-bearing mapping function to the value, otherwise returns an empty Optional.\n\n\n\nBoth map and flatMap can be applied to a Stream<T> and they both return a Stream<R>. When this function is applied to each element of this stream, it constructs a stream of new values. All the generated elements of these new streams are then again copied to a recent stream, which will then act as a return value of this method. The difference is that the map operation produces one output value for each input value, whereas the flatMap operation produces an arbitrary number (zero or more) values for each input value. This is reflected in the arguments to each operation. You can learn more about the flatMap() method in our Java 8 flatMap Example.\n\n\n\nList filteL = listOfOptionals.stream()\n .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())\n .collect(Collectors.toList());\n\n\n\nhashCode() - Returns the hash code of the value, if present, otherwise zero if no value is present.\n\n\n\nThis method\u00e2\u20ac\u2122s functionality is to digest the properties of an object into a single, 32-bit integer value. The hashCode() method should return a unique value for every object, and two objects must not have the same integer hash value, unless they are equal as the equals() method says. You can learn more about the flatMap() method in our Java hashCode method Example.\n\n\n\n@Override\npublic int hashCode() {\n return prefix.hashCode();\n} \n\n\n\nstream() - If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream. (since Java 9)\n\n\n\nThis method converts an Optional into a Stream. If the Optional contains a value it will become a Stream of one element. If the Optional is empty, it will create an empty stream.\n\n\n\n try { \n \n \n System.out.println(\"Stream:\"); \n op.stream().forEach(System.out::println); \n } \n catch (Exception e) { \n System.out.println(e); \n } \n\n\n\nFinally we should mention some simple methods.\n\n\n\nequals() - Indicates whether some other object is \"equal to\" this Optional.\n\n\n\nIndicates whether some other object is \"equal to\" this Optional. The other object is considered equal if:\n\n\n\nit is also an Optionalboth instances have no value presentthe present values are \"equal to\" each other via equals().\n\n\n\nIt also overrides equals in class Object and returns true if the other object is \"equal to\" this object otherwise false.\n\n\n\n System.out.println(\"Comparing first option\"\n + \" and second option: \"\n + op1.equals(op2)); \n\n\n\ntoString() - Returns a non-empty string representation of this Optional suitable for debugging.\n\n\n\nIf a value is present the result must include its string representation in the result. Empty and present Optionals must be unambiguously differentiable.\n\n\n\n String value = op.toString(); \n\n\n\n3. NullPointerException\n\n\n\nFor the ones that do not know what a NullPointerException is, just try:\n\n\n\n\n\n\n\n\n\n1\n2\n\n\n\nString strNull0 = null;\nSystem.out.println( strNull0.contains( \"something\" ) );\n\n\n\n\n\n\n\n\n\n\nThe code above would compile but we would get a warning like:\n\n\n\n\n\n\n\n\n\n1\n\n\n\nNull pointer access: The variable strNull can only be null at this location\n\n\n\n\n\n\n\n\n\n\nIn order to handle this, we can check and validate for null, or we can surround the block with a try catch. In the following chapters we are going to see how to handle this issue using the new Optional class.\n\n\n\n4. Java Optional - Summary\n\n\n\nAnd that's it! In this article, we saw several examples about how to use the new Optional class coming out in Java 8. This class allows us to manage null references in a clear and concise way and to handle the famous NullPointerException more effectively. It is interesting to mention that there are also typified \"optionals\" for the types double, int and long; they work in a similar way than the \"generic\" one, but their values are the ones of the correspondent type and the operations allowed are the ones related to the primitive type.\n\n\n\n5. Additional Links\n\n\n\nFor more information about the Optional class and other methods that we did not mention in this article or about Java 8 features in general, please visit:\n\n\n\nhttp:\/\/docs.oracle.com\/javase\/8\/docs\/api\/index.html?java\/util\/Optional.htmlhttp:\/\/www.javacodegeeks.com\/2014\/05\/java-8-features-tutorial.html\n\n\n\n6. Download the Source Code\n\n\n\nDownloadAll examples from this article (and some more) can be downloaded in the following link: Java 8 Optional Example\n\n\n\nLast Updated on May. 18th, 2020\n","publisher":{"@id":"#Publisher","@type":"Organization","name":"Examples Java Code Geeks","logo":{"@type":"ImageObject","url":"\/wp-content\/uploads\/2013\/05\/JavaCodeGeeks-logo.png"},"sameAs":["https:\/\/feeds.feedburner.com\/examplesjavacodegeeks","https:\/\/www.facebook.com\/javacodegeeks","https:\/\/twitter.com\/javacodegeeks","https:\/\/www.linkedin.com\/groups\/3810709\/","https:\/\/www.youtube.com\/channel\/UCxoUc7Rar2q90Gu0nT2ffuQ","https:\/\/github.com\/javacodegeeks\/"]},"sourceOrganization":{"@id":"#Publisher"},"copyrightHolder":{"@id":"#Publisher"},"mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-8-optional-example\/","breadcrumb":{"@id":"#Breadcrumb"}},"author":{"@type":"Person","name":"Dani Buiza","url":"https:\/\/examples.javacodegeeks.com\/author\/dani-buiza\/"},"image":{"@type":"ImageObject","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":1200,"height":150}}
| og:locale | en_US |
| og:type | article |
| og:site_name | Examples Java Code Geeks |
| article:publisher | https://www.facebook.com/javacodegeeks |
| article:published_time | 2014-08-07T08:00:22+00:00 |
| article:modified_time | 2020-07-23T09:00:48+00:00 |
| og:image | https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg |
| og:image:width | 150 |
| og:image:height | 150 |
| og:image:type | image/jpeg |
| author | Dani Buiza |
| twitter:card | summary_large_image |
| twitter:creator | @javacodegeeks |
| twitter:label1 | Written by |
| twitter:data1 | Dani Buiza |
| twitter:label2 | Est. reading time |
| twitter:data2 | 11 minutes |
| None | IE=edge |
| msapplication-TileImage | https://examples.javacodegeeks.com/wp-content/uploads/2013/05/JavaCodeGeeks-favIcon.png |
Links:
Viewport: width=device-width, initial-scale=1.0
Robots: index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1