├── settings.gradle ├── lib ├── .gitignore ├── src │ ├── main │ │ └── java │ │ │ └── com │ │ │ └── github │ │ │ └── dmstocking │ │ │ └── optional │ │ │ └── java │ │ │ └── util │ │ │ ├── function │ │ │ ├── IntSupplier.java │ │ │ ├── LongSupplier.java │ │ │ ├── DoubleSupplier.java │ │ │ ├── Supplier.java │ │ │ ├── Predicate.java │ │ │ ├── IntConsumer.java │ │ │ ├── LongConsumer.java │ │ │ ├── Function.java │ │ │ ├── DoubleConsumer.java │ │ │ └── Consumer.java │ │ │ ├── OptionalInt.java │ │ │ ├── OptionalLong.java │ │ │ ├── OptionalDouble.java │ │ │ └── Optional.java │ └── test │ │ └── java │ │ └── com │ │ └── github │ │ └── dmstocking │ │ └── optional │ │ └── java │ │ └── util │ │ ├── OptionalIntTest.java │ │ ├── OptionalLongTest.java │ │ ├── OptionalDoubleTest.java │ │ └── OptionalTest.java └── build.gradle ├── .travis.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── local.properties ├── CHANGELOG.md ├── .gitignore ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':lib' 2 | -------------------------------------------------------------------------------- /lib/.gitignore: -------------------------------------------------------------------------------- 1 | gradle.properties 2 | /build/ 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - oraclejdk8 5 | 6 | after_success: 7 | - ./gradlew jacocoTestReport coveralls 8 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dmstocking/support-optional/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Jan 05 21:14:33 EST 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.3-all.zip 7 | -------------------------------------------------------------------------------- /local.properties: -------------------------------------------------------------------------------- 1 | ## This file is automatically generated by Android Studio. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must *NOT* be checked into Version Control Systems, 5 | # as it contains information specific to your local configuration. 6 | # 7 | # Location of the SDK. This is only used by Gradle. 8 | # For customization when using a Version Control System, please read the 9 | # header note. 10 | #Thu Jan 05 21:29:41 EST 2017 11 | sdk.dir=/home/buttink/Android/Sdk 12 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/function/IntSupplier.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util.function; 2 | 3 | /** 4 | * Represents a supplier of results. 5 | * 6 | *

There is no requirement that a new or distinct result be returned each time the supplier is 7 | * invoked. 8 | * 9 | *

This is a functional interface whose functional method is 10 | * {@link #get()}. 11 | */ 12 | public interface IntSupplier { 13 | 14 | /** 15 | * Gets a result. 16 | * 17 | * @return a result 18 | */ 19 | int get(); 20 | } 21 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/function/LongSupplier.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util.function; 2 | 3 | /** 4 | * Represents a supplier of results. 5 | * 6 | *

There is no requirement that a new or distinct result be returned each time the supplier is 7 | * invoked. 8 | * 9 | *

This is a functional interface whose functional method is 10 | * {@link #get()}. 11 | */ 12 | public interface LongSupplier { 13 | 14 | /** 15 | * Gets a result. 16 | * 17 | * @return a result 18 | */ 19 | long get(); 20 | } 21 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/function/DoubleSupplier.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util.function; 2 | 3 | /** 4 | * Represents a supplier of results. 5 | * 6 | *

There is no requirement that a new or distinct result be returned each time the supplier is 7 | * invoked. 8 | * 9 | *

This is a functional interface whose functional method is 10 | * {@link #get()}. 11 | */ 12 | public interface DoubleSupplier { 13 | 14 | /** 15 | * Gets a result. 16 | * 17 | * @return a result 18 | */ 19 | double get(); 20 | } 21 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](http://keepachangelog.com/) 5 | and this project adheres to [Semantic Versioning](http://semver.org/). 6 | 7 | ## [1.2] - 2017-10-14 8 | - Published on JCenter 9 | 10 | ## [1.1] - 2017-01-22 11 | - Optional 12 | - Added ifPresentOrElse 13 | - Added or 14 | - Added OptionalInt 15 | - Added OptionalLong 16 | - Added OptionalDouble 17 | 18 | [1.2]: https://github.com/dmstocking/support-optional/compare/1.1...1.2 19 | [1.1]: https://github.com/dmstocking/support-optional/compare/1.0...1.1 20 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/function/Supplier.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util.function; 2 | 3 | /** 4 | * Represents a supplier of results. 5 | * 6 | *

There is no requirement that a new or distinct result be returned each time the supplier is 7 | * invoked. 8 | * 9 | *

This is a functional interface whose functional method is 10 | * {@link #get()}. 11 | * 12 | * @param the type of results supplied by this supplier 13 | */ 14 | public interface Supplier { 15 | 16 | /** 17 | * Gets a result. 18 | * 19 | * @return a result 20 | */ 21 | T get(); 22 | } 23 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/function/Predicate.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util.function; 2 | 3 | /** 4 | * Represents a predicate (boolean-valued function) of one argument. 5 | * 6 | * This is a functional interface whose functional method is {@code #test(Object)}. 7 | * 8 | * @param the type of the input to the predicate 9 | */ 10 | public interface Predicate { 11 | 12 | /** 13 | * Evaluates this predicate on the given argument. 14 | * 15 | * @param t the input argument 16 | * @return {@code true} if the input argument matches the predicate, otherwise {@code false} 17 | */ 18 | boolean test(T t); 19 | } 20 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/function/IntConsumer.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util.function; 2 | 3 | /** 4 | * Represents an operation that accepts a single input argument and returns no result. Unlike most 5 | * other functional interfaces, {@code Consumer} is expected to operate via side-effects. 6 | * 7 | *

This is a functional interface whose functional method is 8 | * {@link #accept(int)}. 9 | * 10 | * @since 1.8 11 | */ 12 | public interface IntConsumer { 13 | 14 | /** 15 | * Performs this operation on the given argument. 16 | * 17 | * @param value the input argument 18 | */ 19 | void accept(int value); 20 | } 21 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/function/LongConsumer.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util.function; 2 | 3 | /** 4 | * Represents an operation that accepts a single input argument and returns no result. Unlike most 5 | * other functional interfaces, {@code Consumer} is expected to operate via side-effects. 6 | * 7 | *

This is a functional interface whose functional method is 8 | * {@link #accept(long)}. 9 | * 10 | * @since 1.8 11 | */ 12 | public interface LongConsumer { 13 | 14 | /** 15 | * Performs this operation on the given argument. 16 | * 17 | * @param value the input argument 18 | */ 19 | void accept(long value); 20 | } 21 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/function/Function.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util.function; 2 | 3 | /** 4 | * Represents a function that accepts one argument and produces a result. 5 | * 6 | *

This is a functional interface whose functional method is 7 | * {@link #apply(Object)}. 8 | * 9 | * @param the type of the input to the function 10 | * @param the type of the result of the function 11 | */ 12 | public interface Function { 13 | 14 | /** 15 | * Applies this function to the given argument. 16 | * 17 | * @param t the function argument 18 | * @return the function result 19 | */ 20 | R apply(T t); 21 | } 22 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/function/DoubleConsumer.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util.function; 2 | 3 | /** 4 | * Represents an operation that accepts a single input argument and returns no result. Unlike most 5 | * other functional interfaces, {@code Consumer} is expected to operate via side-effects. 6 | * 7 | *

This is a functional interface whose functional method is 8 | * {@link #accept(double)}. 9 | * 10 | * @since 1.8 11 | */ 12 | public interface DoubleConsumer { 13 | 14 | /** 15 | * Performs this operation on the given argument. 16 | * 17 | * @param value the input argument 18 | */ 19 | void accept(double value); 20 | } 21 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/function/Consumer.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util.function; 2 | 3 | /** 4 | * Represents an operation that accepts a single input argument and returns no result. Unlike most 5 | * other functional interfaces, {@code Consumer} is expected to operate via side-effects. 6 | * 7 | *

This is a functional interface whose functional method is 8 | * {@link #accept(Object)}. 9 | * 10 | * @param the type of the input to the operation 11 | * @since 1.8 12 | */ 13 | public interface Consumer { 14 | 15 | /** 16 | * Performs this operation on the given argument. 17 | * 18 | * @param t the input argument 19 | */ 20 | void accept(T t); 21 | } 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #################### 2 | # JetBrains # 3 | #################### 4 | 5 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 6 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 7 | 8 | # User-specific stuff: 9 | .idea/workspace.xml 10 | .idea/tasks.xml 11 | 12 | # Sensitive or high-churn files: 13 | .idea/dataSources/ 14 | .idea/dataSources.ids 15 | .idea/dataSources.xml 16 | .idea/dataSources.local.xml 17 | .idea/sqlDataSources.xml 18 | .idea/dynamic.xml 19 | .idea/uiDesigner.xml 20 | 21 | # Gradle: 22 | .idea/gradle.xml 23 | .idea/libraries 24 | 25 | # Mongo Explorer plugin: 26 | .idea/mongoSettings.xml 27 | 28 | ## File-based project format: 29 | *.iws 30 | 31 | ## Plugin-specific files: 32 | 33 | # IntelliJ 34 | /out/ 35 | 36 | # mpeltonen/sbt-idea plugin 37 | .idea_modules/ 38 | 39 | # JIRA plugin 40 | atlassian-ide-plugin.xml 41 | 42 | # Crashlytics plugin (for Android Studio and IntelliJ) 43 | com_crashlytics_export_strings.xml 44 | crashlytics.properties 45 | crashlytics-build.properties 46 | fabric.properties 47 | 48 | #################### 49 | # Java # 50 | #################### 51 | 52 | *.class 53 | 54 | # BlueJ files 55 | *.ctxt 56 | 57 | # Mobile Tools for Java (J2ME) 58 | .mtj.tmp/ 59 | 60 | # Package Files # 61 | *.jar 62 | *.war 63 | *.ear 64 | 65 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 66 | hs_err_pid* 67 | 68 | #################### 69 | # Gradle # 70 | #################### 71 | 72 | .gradle 73 | /build/ 74 | 75 | # Ignore Gradle GUI config 76 | gradle-app.setting 77 | 78 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 79 | !gradle-wrapper.jar 80 | 81 | # Cache of project 82 | .gradletasknamecache 83 | 84 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 85 | # gradle/wrapper/gradle-wrapper.properties 86 | 87 | -------------------------------------------------------------------------------- /lib/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.github.kt3k.coveralls' version '2.6.3' 3 | id 'com.jfrog.bintray' version '1.7.3' 4 | } 5 | 6 | group 'com.github.dmstocking' 7 | version '1.2' 8 | 9 | apply plugin: 'java' 10 | apply plugin: 'maven' 11 | apply plugin: 'maven-publish' 12 | apply plugin: 'jacoco' 13 | 14 | /* 15 | * If you wish to publish builds, you must provide a gradle.properties 16 | * file in "app" that has two lines 17 | * 18 | * BINTRAY_USER= 19 | * BINTRAY_KEY= 20 | */ 21 | def bintrayUser = hasProperty('BINTRAY_USER') ? BINTRAY_USER : "Do not fill in" 22 | def bintrayKey = hasProperty('BINTRAY_KEY') ? BINTRAY_KEY : "Do not fill in" 23 | 24 | compileJava { 25 | sourceCompatibility = 1.5 26 | targetCompatibility = 1.5 27 | } 28 | 29 | repositories { 30 | mavenCentral() 31 | } 32 | 33 | dependencies { 34 | testCompile group: 'junit', name: 'junit', version: '4.11' 35 | } 36 | 37 | jacocoTestReport { 38 | reports { 39 | xml.enabled = true // coveralls plugin depends on xml format report 40 | html.enabled = true 41 | } 42 | } 43 | 44 | install { 45 | repositories.mavenInstaller { 46 | pom.project { 47 | licenses { 48 | license { 49 | name 'The Apache Software License, Version 2.0' 50 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 51 | distribution 'repo' 52 | } 53 | } 54 | } 55 | } 56 | } 57 | 58 | publishing { 59 | publications { 60 | mavenJava(MavenPublication) { 61 | from components.java 62 | groupId 'com.github.dmstocking' 63 | artifactId 'support-optional' 64 | version '1.2' 65 | artifact (sourcesJar) { 66 | classifier = 'sources' 67 | } 68 | } 69 | } 70 | } 71 | 72 | task sourcesJar(type: Jar, dependsOn: classes) { 73 | classifier = 'sources' 74 | from sourceSets.main.allSource 75 | } 76 | 77 | artifacts { 78 | archives sourcesJar 79 | } 80 | 81 | bintray { 82 | user bintrayUser 83 | key bintrayKey 84 | publications = ['mavenJava'] 85 | pkg { 86 | repo = 'support-optional' 87 | name = 'support-optional' 88 | licenses = ['Apache-2.0'] 89 | vcsUrl = 'https://github.com/dmstocking/support-optional.git' 90 | version { 91 | name = '1.2' 92 | desc = 'support-optional 1.2' 93 | vcsTag = '1.2' 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Download](https://api.bintray.com/packages/buttink/support-optional/support-optional/images/download.svg) ](https://bintray.com/buttink/support-optional/support-optional/_latestVersion) 2 | [![Build Status](https://travis-ci.org/dmstocking/support-optional.svg?branch=master)](https://travis-ci.org/dmstocking/support-optional) 3 | [![Coverage Status](https://coveralls.io/repos/github/dmstocking/support-optional/badge.svg?branch=master)](https://coveralls.io/github/dmstocking/support-optional?branch=master) 4 | 5 | support-optional 6 | =============================================== 7 | 8 | support-optional provides a Java 9 optional that supports Java 6, Android and 9 | RetroLambda development while having an easy migration to the real optional 10 | class. This library is much in the spirit of ActionBarSherlock that it was only 11 | designed to be a removed. 12 | 13 | > It has been deprecated from inception with the intention that you could some 14 | day throw it away.
15 | --Jake Wharton 16 | 17 | Other backports have various problems like different class names, slightly 18 | different behavior or interface default methods. These make it harder to use and 19 | migrate to the real Java 9 optional class. So here is yet another optional 20 | backport, so you don't have to waste your time writing one. 21 | 22 | Download 23 | ----- 24 | Make sure you have the jcenter repository in your root build.gradle 25 | ```gradle 26 | repositories { 27 | jcenter() 28 | } 29 | ``` 30 | 31 | Then add the following to your modules build.gradle file 32 | ```gradle 33 | dependencies { 34 | compile 'com.github.dmstocking:support-optional:1.2' 35 | } 36 | ``` 37 | 38 | Migration 39 | --------- 40 | 41 | Perform the following replacement regex 42 | 43 | ``` 44 | s/com\.github\.dmstocking\.optional\.//g 45 | ``` 46 | 47 | This could be done with find and sed in your project folder via 48 | 49 | ```bash 50 | find . -name "*.java" -exec sed -i 's/com\.github\.dmstocking\.optional\.//g' {} \; 51 | ``` 52 | 53 | or with an IDE so a search and replace without regex of 54 | `com.github.dmstocking.optional.` with nothing over your entire src directory. 55 | 56 | Unavailable Methods 57 | ------------------- 58 | 59 | ``` 60 | - Optional::stream() 61 | - OptionalInt::stream() 62 | - OptionalLong::stream() 63 | - OptionalDouble::stream() 64 | ``` 65 | Because this library does not backport streams, there is no stream method on any of the Optional 66 | classes. 67 | 68 | License 69 | ------- 70 | 71 | ``` 72 | Copyright 2017 David Stocking 73 | 74 | Licensed under the Apache License, Version 2.0 (the "License"); 75 | you may not use this file except in compliance with the License. 76 | You may obtain a copy of the License at 77 | 78 | http://www.apache.org/licenses/LICENSE-2.0 79 | 80 | Unless required by applicable law or agreed to in writing, software 81 | distributed under the License is distributed on an "AS IS" BASIS, 82 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 83 | See the License for the specific language governing permissions and 84 | limitations under the License. 85 | ``` 86 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /lib/src/test/java/com/github/dmstocking/optional/java/util/OptionalIntTest.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util; 2 | 3 | import com.github.dmstocking.optional.java.util.function.IntConsumer; 4 | import com.github.dmstocking.optional.java.util.function.IntSupplier; 5 | import com.github.dmstocking.optional.java.util.function.Supplier; 6 | 7 | import org.junit.Assert; 8 | import org.junit.Test; 9 | 10 | import java.util.NoSuchElementException; 11 | 12 | public class OptionalIntTest { 13 | 14 | @Test 15 | public void emptyIsSameInstanceEveryTime() { 16 | Assert.assertSame(OptionalInt.empty(), OptionalInt.empty()); 17 | } 18 | 19 | @Test 20 | public void getAsIntOfValueReturnsValue() { 21 | OptionalInt of = OptionalInt.of(1); 22 | Assert.assertEquals(1, of.getAsInt()); 23 | } 24 | 25 | @Test(expected = NoSuchElementException.class) 26 | public void getOfEmptyThrowsNoSuchElementException() { 27 | OptionalInt.empty().getAsInt(); 28 | } 29 | 30 | @Test 31 | public void ifPresentOfEmptyDoesNothing() { 32 | final int[] value = {0}; 33 | OptionalInt.empty().ifPresent(new IntConsumer() { 34 | @Override 35 | public void accept(int o) { 36 | value[0] = 1; 37 | } 38 | }); 39 | Assert.assertEquals(0, value[0]); 40 | } 41 | 42 | @Test 43 | public void ifPresentOfValueDoesSomething() { 44 | final int[] value = {0}; 45 | OptionalInt.of(0).ifPresent(new IntConsumer() { 46 | @Override 47 | public void accept(int o) { 48 | value[0] = 1; 49 | } 50 | }); 51 | Assert.assertEquals(1, value[0]); 52 | } 53 | 54 | @Test 55 | public void ifPresentOrElseDoesActionWhenPresent() { 56 | final int[] value = {0}; 57 | OptionalInt.of(0).ifPresentOrElse(new IntConsumer() { 58 | @Override 59 | public void accept(int o) { 60 | value[0] = 1; 61 | } 62 | }, new Runnable() { 63 | @Override 64 | public void run() { 65 | } 66 | }); 67 | Assert.assertEquals(1, value[0]); 68 | } 69 | 70 | @Test 71 | public void ifPresentOrElseDoesEmptyActionWhenEmpty() { 72 | final int[] value = {0}; 73 | OptionalInt.empty().ifPresentOrElse(new IntConsumer() { 74 | @Override 75 | public void accept(int o) { 76 | } 77 | }, new Runnable() { 78 | @Override 79 | public void run() { 80 | value[0] = 1; 81 | } 82 | }); 83 | Assert.assertEquals(1, value[0]); 84 | } 85 | 86 | @Test 87 | public void isPresentOfEmptyReturnsFalse() { 88 | Assert.assertFalse(OptionalInt.empty().isPresent()); 89 | } 90 | 91 | @Test 92 | public void isPresentOfValueReturnsTrue() { 93 | Assert.assertTrue(OptionalInt.of(0).isPresent()); 94 | } 95 | 96 | @Test 97 | public void orElseOfEmptyReturnsElse() { 98 | Assert.assertEquals(1, OptionalInt.empty().orElse(1)); 99 | } 100 | 101 | @Test 102 | public void orElseOfValueReturnsValue() { 103 | Assert.assertEquals(1, OptionalInt.of(1).orElse(2)); 104 | } 105 | 106 | 107 | @Test 108 | public void orElseGetOfEmptyReturnsElse() { 109 | int actual = OptionalInt.empty().orElseGet(new IntSupplier() { 110 | @Override 111 | public int get() { 112 | return 1; 113 | } 114 | }); 115 | Assert.assertEquals(1, actual); 116 | } 117 | 118 | @Test 119 | public void orElseGetOfValueReturnsValue() { 120 | int actual = OptionalInt.of(1).orElseGet(new IntSupplier() { 121 | @Override 122 | public int get() { 123 | return 2; 124 | } 125 | }); 126 | Assert.assertEquals(1, actual); 127 | } 128 | 129 | @Test 130 | public void orElseThrowOfEmptyThrowsException() throws Exception { 131 | final Exception exception = new Exception(); 132 | try { 133 | int actual = OptionalInt.empty().orElseThrow(new Supplier() { 134 | @Override 135 | public Exception get() { 136 | return exception; 137 | } 138 | }); 139 | Assert.fail(); 140 | Assert.assertEquals(0, actual); 141 | } catch (Exception e) { 142 | Assert.assertEquals(exception, e); 143 | } 144 | } 145 | 146 | @Test 147 | public void orElseThrowOfValueReturnsValue() throws Exception { 148 | int actual = OptionalInt.of(1).orElseThrow(new Supplier() { 149 | @Override 150 | public Exception get() { 151 | return new Exception(); 152 | } 153 | }); 154 | Assert.assertEquals(1, actual); 155 | } 156 | 157 | @Test 158 | public void equalsOfValueDoesNotEqualsAnother() throws Exception { 159 | Assert.assertNotEquals(OptionalInt.of(1), OptionalInt.of(2)); 160 | } 161 | 162 | @Test 163 | public void equalsSameReference() throws Exception { 164 | OptionalInt value = OptionalInt.of(1); 165 | Assert.assertEquals(value, value); 166 | } 167 | 168 | @Test 169 | public void equalsOfValueEqualsItself() throws Exception { 170 | Assert.assertEquals(OptionalInt.of(1), OptionalInt.of(1)); 171 | } 172 | 173 | @Test 174 | public void equalsOfValueDoesNotEqualDifferentType() throws Exception { 175 | Assert.assertNotEquals(OptionalInt.of(1), "a"); 176 | } 177 | 178 | @Test 179 | public void equalsOfEmptyDoesNotEqualValue() throws Exception { 180 | Assert.assertNotEquals(OptionalInt.empty(), OptionalInt.of(1)); 181 | } 182 | 183 | @Test 184 | public void hashCodeOfEmptyIsZero() { 185 | Assert.assertEquals(0, OptionalInt.empty().hashCode()); 186 | } 187 | 188 | @Test 189 | public void hashCodeOfValueIsValuesHashCode() { 190 | Assert.assertEquals(Integer.hashCode(1), OptionalInt.of(1).hashCode()); 191 | } 192 | 193 | @Test 194 | public void toStringOfEmpty() { 195 | Assert.assertEquals("OptionalInt.empty", OptionalInt.empty().toString()); 196 | } 197 | 198 | @Test 199 | public void toStringOfValue() { 200 | Assert.assertEquals("OptionalInt[0]", OptionalInt.of(0).toString()); 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /lib/src/test/java/com/github/dmstocking/optional/java/util/OptionalLongTest.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util; 2 | 3 | import com.github.dmstocking.optional.java.util.function.LongConsumer; 4 | import com.github.dmstocking.optional.java.util.function.LongSupplier; 5 | import com.github.dmstocking.optional.java.util.function.Supplier; 6 | 7 | import org.junit.Assert; 8 | import org.junit.Test; 9 | 10 | import java.util.NoSuchElementException; 11 | 12 | public class OptionalLongTest { 13 | 14 | @Test 15 | public void emptyIsSameInstanceEveryTime() { 16 | Assert.assertSame(OptionalLong.empty(), OptionalLong.empty()); 17 | } 18 | 19 | @Test 20 | public void getAsIntOfValueReturnsValue() { 21 | OptionalLong of = OptionalLong.of(1L); 22 | Assert.assertEquals(1L, of.getAsLong()); 23 | } 24 | 25 | @Test(expected = NoSuchElementException.class) 26 | public void getOfEmptyThrowsNoSuchElementException() { 27 | OptionalLong.empty().getAsLong(); 28 | } 29 | 30 | @Test 31 | public void ifPresentOfEmptyDoesNothing() { 32 | final long[] value = {0L}; 33 | OptionalLong.empty().ifPresent(new LongConsumer() { 34 | @Override 35 | public void accept(long o) { 36 | value[0] = 1L; 37 | } 38 | }); 39 | Assert.assertEquals(0L, value[0]); 40 | } 41 | 42 | @Test 43 | public void ifPresentOfValueDoesSomething() { 44 | final long[] value = {0L}; 45 | OptionalLong.of(0L).ifPresent(new LongConsumer() { 46 | @Override 47 | public void accept(long o) { 48 | value[0] = 1L; 49 | } 50 | }); 51 | Assert.assertEquals(1L, value[0]); 52 | } 53 | 54 | @Test 55 | public void ifPresentOrElseDoesActionWhenPresent() { 56 | final long[] value = {0L}; 57 | OptionalLong.of(0L).ifPresentOrElse(new LongConsumer() { 58 | @Override 59 | public void accept(long o) { 60 | value[0] = 1L; 61 | } 62 | }, new Runnable() { 63 | @Override 64 | public void run() { 65 | } 66 | }); 67 | Assert.assertEquals(1L, value[0]); 68 | } 69 | 70 | @Test 71 | public void ifPresentOrElseDoesEmptyActionWhenEmpty() { 72 | final long[] value = {0L}; 73 | OptionalLong.empty().ifPresentOrElse(new LongConsumer() { 74 | @Override 75 | public void accept(long o) { 76 | } 77 | }, new Runnable() { 78 | @Override 79 | public void run() { 80 | value[0] = 1L; 81 | } 82 | }); 83 | Assert.assertEquals(1L, value[0]); 84 | } 85 | 86 | @Test 87 | public void isPresentOfEmptyReturnsFalse() { 88 | Assert.assertFalse(OptionalLong.empty().isPresent()); 89 | } 90 | 91 | @Test 92 | public void isPresentOfValueReturnsTrue() { 93 | Assert.assertTrue(OptionalLong.of(0L).isPresent()); 94 | } 95 | 96 | @Test 97 | public void orElseOfEmptyReturnsElse() { 98 | Assert.assertEquals(1L, OptionalLong.empty().orElse(1L)); 99 | } 100 | 101 | @Test 102 | public void orElseOfValueReturnsValue() { 103 | Assert.assertEquals(1L, OptionalLong.of(1L).orElse(2L)); 104 | } 105 | 106 | 107 | @Test 108 | public void orElseGetOfEmptyReturnsElse() { 109 | long actual = OptionalLong.empty().orElseGet(new LongSupplier() { 110 | @Override 111 | public long get() { 112 | return 1L; 113 | } 114 | }); 115 | Assert.assertEquals(1L, actual); 116 | } 117 | 118 | @Test 119 | public void orElseGetOfValueReturnsValue() { 120 | long actual = OptionalLong.of(1L).orElseGet(new LongSupplier() { 121 | @Override 122 | public long get() { 123 | return 2L; 124 | } 125 | }); 126 | Assert.assertEquals(1L, actual); 127 | } 128 | 129 | @Test 130 | public void orElseThrowOfEmptyThrowsException() throws Exception { 131 | final Exception exception = new Exception(); 132 | try { 133 | long actual = OptionalLong.empty().orElseThrow(new Supplier() { 134 | @Override 135 | public Exception get() { 136 | return exception; 137 | } 138 | }); 139 | Assert.fail(); 140 | Assert.assertEquals(0L, actual); 141 | } catch (Exception e) { 142 | Assert.assertEquals(exception, e); 143 | } 144 | } 145 | 146 | @Test 147 | public void orElseThrowOfValueReturnsValue() throws Exception { 148 | long actual = OptionalLong.of(1L).orElseThrow(new Supplier() { 149 | @Override 150 | public Exception get() { 151 | return new Exception(); 152 | } 153 | }); 154 | Assert.assertEquals(1L, actual); 155 | } 156 | 157 | @Test 158 | public void equalsOfValueDoesNotEqualsAnother() throws Exception { 159 | Assert.assertNotEquals(OptionalLong.of(1L), OptionalLong.of(2L)); 160 | } 161 | 162 | @Test 163 | public void equalsSameReference() throws Exception { 164 | OptionalLong value = OptionalLong.of(1L); 165 | Assert.assertEquals(value, value); 166 | } 167 | 168 | @Test 169 | public void equalsOfValueEqualsItself() throws Exception { 170 | Assert.assertEquals(OptionalLong.of(1L), OptionalLong.of(1L)); 171 | } 172 | 173 | @Test 174 | public void equalsOfValueDoesNotEqualDifferentType() throws Exception { 175 | Assert.assertNotEquals(OptionalLong.of(1L), "a"); 176 | } 177 | 178 | @Test 179 | public void equalsOfEmptyDoesNotEqualValue() throws Exception { 180 | Assert.assertNotEquals(OptionalLong.empty(), OptionalLong.of(1L)); 181 | } 182 | 183 | @Test 184 | public void hashCodeOfEmptyIsZero() { 185 | Assert.assertEquals(0L, OptionalLong.empty().hashCode()); 186 | } 187 | 188 | @Test 189 | public void hashCodeOfValueIsValuesHashCode() { 190 | Assert.assertEquals(Long.hashCode(1L), OptionalLong.of(1L).hashCode()); 191 | } 192 | 193 | @Test 194 | public void toStringOfEmpty() { 195 | Assert.assertEquals("OptionalLong.empty", OptionalLong.empty().toString()); 196 | } 197 | 198 | @Test 199 | public void toStringOfValue() { 200 | Assert.assertEquals("OptionalLong[0]", OptionalLong.of(0L).toString()); 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /lib/src/test/java/com/github/dmstocking/optional/java/util/OptionalDoubleTest.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util; 2 | 3 | import com.github.dmstocking.optional.java.util.function.DoubleConsumer; 4 | import com.github.dmstocking.optional.java.util.function.DoubleSupplier; 5 | import com.github.dmstocking.optional.java.util.function.Supplier; 6 | 7 | import org.junit.Assert; 8 | import org.junit.Test; 9 | 10 | import java.util.NoSuchElementException; 11 | 12 | public class OptionalDoubleTest { 13 | 14 | @Test 15 | public void emptyIsSameInstanceEveryTime() { 16 | Assert.assertSame(OptionalDouble.empty(), OptionalDouble.empty()); 17 | } 18 | 19 | @Test 20 | public void getAsIntOfValueReturnsValue() { 21 | OptionalDouble of = OptionalDouble.of(1.0); 22 | Assert.assertEquals(1.0, of.getAsDouble(), 0.0); 23 | } 24 | 25 | @Test(expected = NoSuchElementException.class) 26 | public void getOfEmptyThrowsNoSuchElementException() { 27 | OptionalDouble.empty().getAsDouble(); 28 | } 29 | 30 | @Test 31 | public void ifPresentOfEmptyDoesNothing() { 32 | final double[] value = {0.0}; 33 | OptionalDouble.empty().ifPresent(new DoubleConsumer() { 34 | @Override 35 | public void accept(double o) { 36 | value[0] = 1.0; 37 | } 38 | }); 39 | Assert.assertEquals(0.0, value[0], 0.0); 40 | } 41 | 42 | @Test 43 | public void ifPresentOfValueDoesSomething() { 44 | final double[] value = {0.0}; 45 | OptionalDouble.of(0.0).ifPresent(new DoubleConsumer() { 46 | @Override 47 | public void accept(double o) { 48 | value[0] = 1.0; 49 | } 50 | }); 51 | Assert.assertEquals(1.0, value[0], 0.0); 52 | } 53 | 54 | @Test 55 | public void ifPresentOrElseDoesActionWhenPresent() { 56 | final double[] value = {0.0}; 57 | OptionalDouble.of(0.0).ifPresentOrElse(new DoubleConsumer() { 58 | @Override 59 | public void accept(double o) { 60 | value[0] = 1.0; 61 | } 62 | }, new Runnable() { 63 | @Override 64 | public void run() { 65 | } 66 | }); 67 | Assert.assertEquals(1.0, value[0], 0.0); 68 | } 69 | 70 | @Test 71 | public void ifPresentOrElseDoesEmptyActionWhenEmpty() { 72 | final double[] value = {0.0}; 73 | OptionalDouble.empty().ifPresentOrElse(new DoubleConsumer() { 74 | @Override 75 | public void accept(double o) { 76 | } 77 | }, new Runnable() { 78 | @Override 79 | public void run() { 80 | value[0] = 1.0; 81 | } 82 | }); 83 | Assert.assertEquals(1.0, value[0], 0.0); 84 | } 85 | 86 | @Test 87 | public void isPresentOfEmptyReturnsFalse() { 88 | Assert.assertFalse(OptionalDouble.empty().isPresent()); 89 | } 90 | 91 | @Test 92 | public void isPresentOfValueReturnsTrue() { 93 | Assert.assertTrue(OptionalDouble.of(0.0).isPresent()); 94 | } 95 | 96 | @Test 97 | public void orElseOfEmptyReturnsElse() { 98 | Assert.assertEquals(1.0, OptionalDouble.empty().orElse(1.0), 0.0); 99 | } 100 | 101 | @Test 102 | public void orElseOfValueReturnsValue() { 103 | Assert.assertEquals(1.0, OptionalDouble.of(1.0).orElse(2.0), 0.0); 104 | } 105 | 106 | 107 | @Test 108 | public void orElseGetOfEmptyReturnsElse() { 109 | double actual = OptionalDouble.empty().orElseGet(new DoubleSupplier() { 110 | @Override 111 | public double get() { 112 | return 1.0; 113 | } 114 | }); 115 | Assert.assertEquals(1.0, actual, 0.0); 116 | } 117 | 118 | @Test 119 | public void orElseGetOfValueReturnsValue() { 120 | double actual = OptionalDouble.of(1.0).orElseGet(new DoubleSupplier() { 121 | @Override 122 | public double get() { 123 | return 2.0; 124 | } 125 | }); 126 | Assert.assertEquals(1.0, actual, 0.0); 127 | } 128 | 129 | @Test 130 | public void orElseThrowOfEmptyThrowsException() throws Exception { 131 | final Exception exception = new Exception(); 132 | try { 133 | double actual = OptionalDouble.empty().orElseThrow(new Supplier() { 134 | @Override 135 | public Exception get() { 136 | return exception; 137 | } 138 | }); 139 | Assert.fail(); 140 | Assert.assertEquals(0.0, actual); 141 | } catch (Exception e) { 142 | Assert.assertEquals(exception, e); 143 | } 144 | } 145 | 146 | @Test 147 | public void orElseThrowOfValueReturnsValue() throws Exception { 148 | double actual = OptionalDouble.of(1.0).orElseThrow(new Supplier() { 149 | @Override 150 | public Exception get() { 151 | return new Exception(); 152 | } 153 | }); 154 | Assert.assertEquals(1.0, actual, 0.0); 155 | } 156 | 157 | @Test 158 | public void equalsOfValueDoesNotEqualsAnother() throws Exception { 159 | Assert.assertNotEquals(OptionalDouble.of(1.0), OptionalDouble.of(2.0)); 160 | } 161 | 162 | @Test 163 | public void equalsSameReference() throws Exception { 164 | OptionalDouble value = OptionalDouble.of(1.0); 165 | Assert.assertEquals(value, value); 166 | } 167 | 168 | @Test 169 | public void equalsOfValueEqualsItself() throws Exception { 170 | Assert.assertEquals(OptionalDouble.of(1.0), OptionalDouble.of(1.0)); 171 | } 172 | 173 | @Test 174 | public void equalsOfValueDoesNotEqualDifferentType() throws Exception { 175 | Assert.assertNotEquals(OptionalDouble.of(1.0), "a"); 176 | } 177 | 178 | @Test 179 | public void equalsOfEmptyDoesNotEqualValue() throws Exception { 180 | Assert.assertNotEquals(OptionalDouble.empty(), OptionalDouble.of(1.0)); 181 | } 182 | 183 | @Test 184 | public void hashCodeOfEmptyIsZero() { 185 | Assert.assertEquals(0, OptionalDouble.empty().hashCode()); 186 | } 187 | 188 | @Test 189 | public void hashCodeOfValueIsValuesHashCode() { 190 | Assert.assertEquals(Double.hashCode(1.0), OptionalDouble.of(1.0).hashCode()); 191 | } 192 | 193 | @Test 194 | public void toStringOfEmpty() { 195 | Assert.assertEquals("OptionalDouble.empty", OptionalDouble.empty().toString()); 196 | } 197 | 198 | @Test 199 | public void toStringOfValue() { 200 | Assert.assertEquals("OptionalDouble[0.0]", OptionalDouble.of(0.0d).toString()); 201 | } 202 | } 203 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/OptionalInt.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util; 2 | 3 | import com.github.dmstocking.optional.java.util.function.IntConsumer; 4 | import com.github.dmstocking.optional.java.util.function.IntSupplier; 5 | import com.github.dmstocking.optional.java.util.function.Supplier; 6 | 7 | import java.util.NoSuchElementException; 8 | 9 | /** 10 | * A container object which may or may not contain a non-null value. If a value is present, {@code 11 | * isPresent()} will return {@code true} and {@code get()} will return the value. 12 | * 13 | * Additional methods that depend on the presence or absence of a contained value are provided, such 14 | * as {@code orElse()} (return a default value if value not present) and {@code ifPresent()} 15 | * (execute a block of code if the value is present). 16 | */ 17 | @SuppressWarnings("WeakerAccess") 18 | public final class OptionalInt { 19 | 20 | private static final OptionalInt EMPTY = new OptionalInt(false, 0); 21 | 22 | /** 23 | * Returns an empty {@code Optional} instance. No value is present for this Optional. 24 | * 25 | * Though it may be tempting to do so, avoid testing if an object is empty by comparing with 26 | * {@code ==} against instances returned by {@code Optional.empty()}. There is no guarantee that 27 | * it is a singleton. Instead, use {@link #isPresent()} 28 | * 29 | * @return an empty {@code Optional} 30 | */ 31 | public static OptionalInt empty() { 32 | return EMPTY; 33 | } 34 | 35 | private boolean isPresent; 36 | private final int value; 37 | 38 | private OptionalInt(boolean isPresent, int value) { 39 | this.isPresent = isPresent; 40 | this.value = value; 41 | } 42 | 43 | /** 44 | * Returns an Optional with the specified present non-null value. 45 | * 46 | * @param value the value to be present, which must be non-null 47 | * @return an Optional with the value present 48 | */ 49 | public static OptionalInt of(int value) { 50 | return new OptionalInt(true, value); 51 | } 52 | 53 | /** 54 | * If a value is present in this {@code Optional}, returns the value, otherwise throws {@code 55 | * NoSuchElementException}. 56 | * 57 | * @return the non-null value held by this {@code Optional} 58 | * @throws NoSuchElementException if there is no value present 59 | * @see OptionalInt#isPresent() 60 | */ 61 | public int getAsInt() { 62 | if (isPresent()) { 63 | return value; 64 | } 65 | 66 | throw new NoSuchElementException("No value present"); 67 | } 68 | 69 | /** 70 | * If a value is present, invoke the specified consumer with the value, otherwise do nothing. 71 | * 72 | * @param consumer block to be executed if a value is present 73 | * @throws NullPointerException if value is present and {@code consumer} is null 74 | */ 75 | public void ifPresent(IntConsumer consumer) { 76 | if (isPresent()) { 77 | consumer.accept(value); 78 | } 79 | } 80 | 81 | /** 82 | * If a value is present, invoke the specified consumer with the value, otherwise performs the 83 | * given empty-based aciton. 84 | * 85 | * @param consumer block to be executed if a value is present 86 | * @param emptyAction the empty-based action to be performed, if no value is present 87 | * @throws NullPointerException if value is present and {@code consumer} is null, or no value is 88 | * present and the given empty-based action is null. 89 | */ 90 | public void ifPresentOrElse(IntConsumer consumer, Runnable emptyAction) { 91 | if (isPresent()) { 92 | consumer.accept(value); 93 | } else { 94 | emptyAction.run(); 95 | } 96 | } 97 | 98 | public boolean isPresent() { 99 | return isPresent; 100 | } 101 | 102 | /** 103 | * Return the value if present, otherwise return {@code other}. 104 | * 105 | * @param other the value to be returned if there is no value present, may be null 106 | * @return the value, if present, otherwise {@code other} 107 | */ 108 | public int orElse(int other) { 109 | if (isPresent()) { 110 | return value; 111 | } 112 | 113 | return other; 114 | } 115 | 116 | /** 117 | * Return the value if present, otherwise invoke {@code other} and return the result of that 118 | * invocation. 119 | * 120 | * @param other a {@code Supplier} whose result is returned if no value is present 121 | * @return the value if present otherwise the result of {@code other.get()} 122 | * @throws NullPointerException if value is not present and {@code other} is null 123 | */ 124 | public int orElseGet(IntSupplier other) { 125 | if (isPresent()) { 126 | return value; 127 | } 128 | 129 | return other.get(); 130 | } 131 | 132 | /** 133 | * Return the contained value, if present, otherwise throw an exception to be created by the 134 | * provided supplier. 135 | * 136 | *

A method reference to the exception constructor with an empty argument list can be used 137 | * as the supplier. For example, {@code IllegalStateException::new}

138 | * 139 | * @param Type of the exception to be thrown 140 | * @param exceptionSupplier The supplier which will return the exception to be thrown 141 | * @return the present value 142 | * @throws X if there is no value present 143 | * @throws NullPointerException if no value is present and {@code exceptionSupplier} is null 144 | */ 145 | public int orElseThrow(Supplier exceptionSupplier) throws X { 146 | if (isPresent()) { 147 | return value; 148 | } 149 | 150 | throw exceptionSupplier.get(); 151 | } 152 | 153 | /** 154 | * Indicates whether some other object is "equal to" this Optional. The other object is 155 | * considered equal if: 158 | * 159 | * @param o an object to be tested for equality 160 | * @return {code true} if the other object is "equal to" this object otherwise {@code false} 161 | */ 162 | @Override 163 | public boolean equals(Object o) { 164 | if (this == o) { 165 | return true; 166 | } 167 | 168 | if (!(o instanceof OptionalInt)) { 169 | return false; 170 | } 171 | 172 | if (isPresent()) { 173 | OptionalInt other = (OptionalInt) o; 174 | return value == other.value; 175 | } 176 | 177 | return false; 178 | } 179 | 180 | /** 181 | * Returns the hash code value of the present value, if any, or 0 (zero) if no value is 182 | * present. 183 | * 184 | * @return hash code value of the present value or 0 if no value is present 185 | */ 186 | @Override 187 | public int hashCode() { 188 | if (isPresent()) { 189 | return Integer.hashCode(value); 190 | } 191 | 192 | return 0; 193 | } 194 | 195 | /** 196 | * Returns a non-empty string representation of this Optional suitable for debugging. The exact 197 | * presentation format is unspecified and may vary between implementations and versions. 198 | * 199 | *

If a value is present the result must include its string representation in the result. 200 | * Empty and present Optionals must be unambiguously differentiable.

201 | * 202 | * @return the string representation of this instance 203 | */ 204 | @Override 205 | public String toString() { 206 | if (isPresent()) { 207 | return "OptionalInt[" + value + "]"; 208 | } 209 | 210 | return "OptionalInt.empty"; 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/OptionalLong.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util; 2 | 3 | import com.github.dmstocking.optional.java.util.function.LongConsumer; 4 | import com.github.dmstocking.optional.java.util.function.LongSupplier; 5 | import com.github.dmstocking.optional.java.util.function.Supplier; 6 | 7 | import java.util.NoSuchElementException; 8 | 9 | /** 10 | * A container object which may or may not contain a non-null value. If a value is present, {@code 11 | * isPresent()} will return {@code true} and {@code get()} will return the value. 12 | * 13 | * Additional methods that depend on the presence or absence of a contained value are provided, such 14 | * as {@code orElse()} (return a default value if value not present) and {@code ifPresent()} 15 | * (execute a block of code if the value is present). 16 | */ 17 | @SuppressWarnings("WeakerAccess") 18 | public final class OptionalLong { 19 | 20 | private static final OptionalLong EMPTY = new OptionalLong(false, 0); 21 | 22 | /** 23 | * Returns an empty {@code Optional} instance. No value is present for this Optional. 24 | * 25 | * Though it may be tempting to do so, avoid testing if an object is empty by comparing with 26 | * {@code ==} against instances returned by {@code Optional.empty()}. There is no guarantee that 27 | * it is a singleton. Instead, use {@link #isPresent()} 28 | * 29 | * @return an empty {@code Optional} 30 | */ 31 | public static OptionalLong empty() { 32 | return EMPTY; 33 | } 34 | 35 | private boolean isPresent; 36 | private final long value; 37 | 38 | private OptionalLong(boolean isPresent, long value) { 39 | this.isPresent = isPresent; 40 | this.value = value; 41 | } 42 | 43 | /** 44 | * Returns an Optional with the specified present non-null value. 45 | * 46 | * @param value the value to be present, which must be non-null 47 | * @return an Optional with the value present 48 | */ 49 | public static OptionalLong of(long value) { 50 | return new OptionalLong(true, value); 51 | } 52 | 53 | /** 54 | * If a value is present in this {@code Optional}, returns the value, otherwise throws {@code 55 | * NoSuchElementException}. 56 | * 57 | * @return the non-null value held by this {@code Optional} 58 | * @throws NoSuchElementException if there is no value present 59 | * @see OptionalLong#isPresent() 60 | */ 61 | public long getAsLong() { 62 | if (isPresent()) { 63 | return value; 64 | } 65 | 66 | throw new NoSuchElementException("No value present"); 67 | } 68 | 69 | /** 70 | * If a value is present, invoke the specified consumer with the value, otherwise do nothing. 71 | * 72 | * @param consumer block to be executed if a value is present 73 | * @throws NullPointerException if value is present and {@code consumer} is null 74 | */ 75 | public void ifPresent(LongConsumer consumer) { 76 | if (isPresent()) { 77 | consumer.accept(value); 78 | } 79 | } 80 | 81 | /** 82 | * If a value is present, invoke the specified consumer with the value, otherwise performs the 83 | * given empty-based aciton. 84 | * 85 | * @param consumer block to be executed if a value is present 86 | * @param emptyAction the empty-based action to be performed, if no value is present 87 | * @throws NullPointerException if value is present and {@code consumer} is null, or no value is 88 | * present and the given empty-based action is null. 89 | */ 90 | public void ifPresentOrElse(LongConsumer consumer, Runnable emptyAction) { 91 | if (isPresent()) { 92 | consumer.accept(value); 93 | } else { 94 | emptyAction.run(); 95 | } 96 | } 97 | 98 | public boolean isPresent() { 99 | return isPresent; 100 | } 101 | 102 | /** 103 | * Return the value if present, otherwise return {@code other}. 104 | * 105 | * @param other the value to be returned if there is no value present, may be null 106 | * @return the value, if present, otherwise {@code other} 107 | */ 108 | public long orElse(long other) { 109 | if (isPresent()) { 110 | return value; 111 | } 112 | 113 | return other; 114 | } 115 | 116 | /** 117 | * Return the value if present, otherwise invoke {@code other} and return the result of that 118 | * invocation. 119 | * 120 | * @param other a {@code Supplier} whose result is returned if no value is present 121 | * @return the value if present otherwise the result of {@code other.get()} 122 | * @throws NullPointerException if value is not present and {@code other} is null 123 | */ 124 | public long orElseGet(LongSupplier other) { 125 | if (isPresent()) { 126 | return value; 127 | } 128 | 129 | return other.get(); 130 | } 131 | 132 | /** 133 | * Return the contained value, if present, otherwise throw an exception to be created by the 134 | * provided supplier. 135 | * 136 | *

A method reference to the exception constructor with an empty argument list can be used 137 | * as the supplier. For example, {@code IllegalStateException::new}

138 | * 139 | * @param Type of the exception to be thrown 140 | * @param exceptionSupplier The supplier which will return the exception to be thrown 141 | * @return the present value 142 | * @throws X if there is no value present 143 | * @throws NullPointerException if no value is present and {@code exceptionSupplier} is null 144 | */ 145 | public long orElseThrow(Supplier exceptionSupplier) throws X { 146 | if (isPresent()) { 147 | return value; 148 | } 149 | 150 | throw exceptionSupplier.get(); 151 | } 152 | 153 | /** 154 | * Indicates whether some other object is "equal to" this Optional. The other object is 155 | * considered equal if:
  • it is also an {@code Optional} and;
  • both instances have no 156 | * value present or;
  • the present values are "equal to" each other via {@code equals()}. 157 | *
158 | * 159 | * @param o an object to be tested for equality 160 | * @return {code true} if the other object is "equal to" this object otherwise {@code false} 161 | */ 162 | @Override 163 | public boolean equals(Object o) { 164 | if (this == o) { 165 | return true; 166 | } 167 | 168 | if (!(o instanceof OptionalLong)) { 169 | return false; 170 | } 171 | 172 | if (isPresent()) { 173 | OptionalLong other = (OptionalLong) o; 174 | return value == other.value; 175 | } 176 | 177 | return false; 178 | } 179 | 180 | /** 181 | * Returns the hash code value of the present value, if any, or 0 (zero) if no value is 182 | * present. 183 | * 184 | * @return hash code value of the present value or 0 if no value is present 185 | */ 186 | @Override 187 | public int hashCode() { 188 | if (isPresent()) { 189 | return Long.hashCode(value); 190 | } 191 | 192 | return 0; 193 | } 194 | 195 | /** 196 | * Returns a non-empty string representation of this Optional suitable for debugging. The exact 197 | * presentation format is unspecified and may vary between implementations and versions. 198 | * 199 | *

If a value is present the result must include its string representation in the result. 200 | * Empty and present Optionals must be unambiguously differentiable.

201 | * 202 | * @return the string representation of this instance 203 | */ 204 | @Override 205 | public String toString() { 206 | if (isPresent()) { 207 | return "OptionalLong[" + value + "]"; 208 | } 209 | 210 | return "OptionalLong.empty"; 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/OptionalDouble.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util; 2 | 3 | import com.github.dmstocking.optional.java.util.function.DoubleConsumer; 4 | import com.github.dmstocking.optional.java.util.function.DoubleSupplier; 5 | import com.github.dmstocking.optional.java.util.function.Supplier; 6 | 7 | import java.util.NoSuchElementException; 8 | 9 | /** 10 | * A container object which may or may not contain a non-null value. If a value is present, {@code 11 | * isPresent()} will return {@code true} and {@code get()} will return the value. 12 | * 13 | * Additional methods that depend on the presence or absence of a contained value are provided, such 14 | * as {@code orElse()} (return a default value if value not present) and {@code ifPresent()} 15 | * (execute a block of code if the value is present). 16 | */ 17 | @SuppressWarnings("WeakerAccess") 18 | public final class OptionalDouble { 19 | 20 | private static final OptionalDouble EMPTY = new OptionalDouble(false, 0); 21 | 22 | /** 23 | * Returns an empty {@code Optional} instance. No value is present for this Optional. 24 | * 25 | * Though it may be tempting to do so, avoid testing if an object is empty by comparing with 26 | * {@code ==} against instances returned by {@code Optional.empty()}. There is no guarantee that 27 | * it is a singleton. Instead, use {@link #isPresent()} 28 | * 29 | * @return an empty {@code Optional} 30 | */ 31 | public static OptionalDouble empty() { 32 | return EMPTY; 33 | } 34 | 35 | private boolean isPresent; 36 | private final double value; 37 | 38 | private OptionalDouble(boolean isPresent, double value) { 39 | this.isPresent = isPresent; 40 | this.value = value; 41 | } 42 | 43 | /** 44 | * Returns an Optional with the specified present non-null value. 45 | * 46 | * @param value the value to be present, which must be non-null 47 | * @return an Optional with the value present 48 | */ 49 | public static OptionalDouble of(double value) { 50 | return new OptionalDouble(true, value); 51 | } 52 | 53 | /** 54 | * If a value is present in this {@code Optional}, returns the value, otherwise throws {@code 55 | * NoSuchElementException}. 56 | * 57 | * @return the non-null value held by this {@code Optional} 58 | * @throws NoSuchElementException if there is no value present 59 | * @see OptionalDouble#isPresent() 60 | */ 61 | public double getAsDouble() { 62 | if (isPresent()) { 63 | return value; 64 | } 65 | 66 | throw new NoSuchElementException("No value present"); 67 | } 68 | 69 | /** 70 | * If a value is present, invoke the specified consumer with the value, otherwise do nothing. 71 | * 72 | * @param consumer block to be executed if a value is present 73 | * @throws NullPointerException if value is present and {@code consumer} is null 74 | */ 75 | public void ifPresent(DoubleConsumer consumer) { 76 | if (isPresent()) { 77 | consumer.accept(value); 78 | } 79 | } 80 | 81 | /** 82 | * If a value is present, invoke the specified consumer with the value, otherwise performs the 83 | * given empty-based aciton. 84 | * 85 | * @param consumer block to be executed if a value is present 86 | * @param emptyAction the empty-based action to be performed, if no value is present 87 | * @throws NullPointerException if value is present and {@code consumer} is null, or no value is 88 | * present and the given empty-based action is null. 89 | */ 90 | public void ifPresentOrElse(DoubleConsumer consumer, Runnable emptyAction) { 91 | if (isPresent()) { 92 | consumer.accept(value); 93 | } else { 94 | emptyAction.run(); 95 | } 96 | } 97 | 98 | public boolean isPresent() { 99 | return isPresent; 100 | } 101 | 102 | /** 103 | * Return the value if present, otherwise return {@code other}. 104 | * 105 | * @param other the value to be returned if there is no value present, may be null 106 | * @return the value, if present, otherwise {@code other} 107 | */ 108 | public double orElse(double other) { 109 | if (isPresent()) { 110 | return value; 111 | } 112 | 113 | return other; 114 | } 115 | 116 | /** 117 | * Return the value if present, otherwise invoke {@code other} and return the result of that 118 | * invocation. 119 | * 120 | * @param other a {@code Supplier} whose result is returned if no value is present 121 | * @return the value if present otherwise the result of {@code other.get()} 122 | * @throws NullPointerException if value is not present and {@code other} is null 123 | */ 124 | public double orElseGet(DoubleSupplier other) { 125 | if (isPresent()) { 126 | return value; 127 | } 128 | 129 | return other.get(); 130 | } 131 | 132 | /** 133 | * Return the contained value, if present, otherwise throw an exception to be created by the 134 | * provided supplier. 135 | * 136 | *

A method reference to the exception constructor with an empty argument list can be used 137 | * as the supplier. For example, {@code IllegalStateException::new}

138 | * 139 | * @param Type of the exception to be thrown 140 | * @param exceptionSupplier The supplier which will return the exception to be thrown 141 | * @return the present value 142 | * @throws X if there is no value present 143 | * @throws NullPointerException if no value is present and {@code exceptionSupplier} is null 144 | */ 145 | public double orElseThrow(Supplier exceptionSupplier) throws X { 146 | if (isPresent()) { 147 | return value; 148 | } 149 | 150 | throw exceptionSupplier.get(); 151 | } 152 | 153 | /** 154 | * Indicates whether some other object is "equal to" this Optional. The other object is 155 | * considered equal if:
  • it is also an {@code Optional} and;
  • both instances have no 156 | * value present or;
  • the present values are "equal to" each other via {@code equals()}. 157 | *
158 | * 159 | * @param o an object to be tested for equality 160 | * @return {code true} if the other object is "equal to" this object otherwise {@code false} 161 | */ 162 | @Override 163 | public boolean equals(Object o) { 164 | if (this == o) { 165 | return true; 166 | } 167 | 168 | if (!(o instanceof OptionalDouble)) { 169 | return false; 170 | } 171 | 172 | if (isPresent()) { 173 | OptionalDouble other = (OptionalDouble) o; 174 | return value == other.value; 175 | } 176 | 177 | return false; 178 | } 179 | 180 | /** 181 | * Returns the hash code value of the present value, if any, or 0 (zero) if no value is 182 | * present. 183 | * 184 | * @return hash code value of the present value or 0 if no value is present 185 | */ 186 | @Override 187 | public int hashCode() { 188 | if (isPresent()) { 189 | return Double.hashCode(value); 190 | } 191 | 192 | return 0; 193 | } 194 | 195 | /** 196 | * Returns a non-empty string representation of this Optional suitable for debugging. The exact 197 | * presentation format is unspecified and may vary between implementations and versions. 198 | * 199 | *

If a value is present the result must include its string representation in the result. 200 | * Empty and present Optionals must be unambiguously differentiable.

201 | * 202 | * @return the string representation of this instance 203 | */ 204 | @Override 205 | public String toString() { 206 | if (isPresent()) { 207 | return "OptionalDouble[" + value + "]"; 208 | } 209 | 210 | return "OptionalDouble.empty"; 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /lib/src/test/java/com/github/dmstocking/optional/java/util/OptionalTest.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util; 2 | 3 | import com.github.dmstocking.optional.java.util.function.Consumer; 4 | import com.github.dmstocking.optional.java.util.function.Function; 5 | import com.github.dmstocking.optional.java.util.function.Predicate; 6 | import com.github.dmstocking.optional.java.util.function.Supplier; 7 | 8 | import org.junit.Assert; 9 | import org.junit.Test; 10 | 11 | import java.util.NoSuchElementException; 12 | 13 | public class OptionalTest { 14 | 15 | @Test 16 | public void emptyIsSameInstanceEveryTime() { 17 | Assert.assertSame(Optional.empty(), Optional.empty()); 18 | } 19 | 20 | @Test(expected = NullPointerException.class) 21 | public void ofWithNullThrowsNPException() { 22 | Optional.of(null); 23 | } 24 | 25 | @Test 26 | public void ofNullableWithNullReturnsEmpty() { 27 | Assert.assertEquals(Optional.empty(), Optional.ofNullable(null)); 28 | } 29 | 30 | @Test 31 | public void filterOfEmptyWithFalsePredicateReturnsEmpty() { 32 | Optional filtered = Optional.empty().filter(new Predicate() { 33 | @Override 34 | public boolean test(Object object) { 35 | return false; 36 | } 37 | }); 38 | 39 | Assert.assertEquals(Optional.empty(), filtered); 40 | } 41 | 42 | @Test 43 | public void filterOfEmptyWithTruePredicateReturnsEmpty() { 44 | Optional filtered = Optional.empty().filter(new Predicate() { 45 | @Override 46 | public boolean test(Object object) { 47 | return true; 48 | } 49 | }); 50 | 51 | Assert.assertEquals(Optional.empty(), filtered); 52 | } 53 | 54 | @Test 55 | public void filterOfValueWithFalsePredicateReturnsEmpty() { 56 | Optional filtered = Optional.of(0).filter(new Predicate() { 57 | @Override 58 | public boolean test(Integer object) { 59 | return false; 60 | } 61 | }); 62 | 63 | Assert.assertEquals(Optional.empty(), filtered); 64 | } 65 | 66 | @Test 67 | public void filterOfValueWithTruePredicateReturnsValue() { 68 | Optional filtered = Optional.of(0).filter(new Predicate() { 69 | @Override 70 | public boolean test(Integer object) { 71 | return true; 72 | } 73 | }); 74 | 75 | Assert.assertEquals(Optional.of(0), filtered); 76 | } 77 | 78 | @Test 79 | public void flatMapOfEmptyReturnsValue() { 80 | Optional empty = Optional.empty(); 81 | Optional mapped = empty.flatMap(new Function>() { 82 | @Override 83 | public Optional apply(Integer integer) { 84 | return Optional.of("mapped"); 85 | } 86 | }); 87 | 88 | Assert.assertEquals(Optional.empty(), mapped); 89 | } 90 | 91 | @Test 92 | public void flatMapOfValueReturnsMappedValue() { 93 | Optional mapped = Optional.of(0).flatMap(new Function>() { 94 | @Override 95 | public Optional apply(Integer integer) { 96 | return Optional.of("mapped"); 97 | } 98 | }); 99 | 100 | Assert.assertEquals(Optional.of("mapped"), mapped); 101 | } 102 | 103 | @Test 104 | public void getOfValueReturnsValue() { 105 | Optional of = Optional.of("value"); 106 | Assert.assertEquals("value", of.get()); 107 | } 108 | 109 | @Test(expected = NoSuchElementException.class) 110 | public void getOfEmptyThrowsNoSuchElementException() { 111 | Optional.empty().get(); 112 | } 113 | 114 | @Test 115 | public void ifPresentOfEmptyDoesNothing() { 116 | final int[] value = {0}; 117 | Optional.empty().ifPresent(new Consumer() { 118 | @Override 119 | public void accept(Object o) { 120 | value[0] = 1; 121 | } 122 | }); 123 | Assert.assertEquals(0, value[0]); 124 | } 125 | 126 | @Test 127 | public void ifPresentOfValueDoesSomething() { 128 | final int[] value = {0}; 129 | Optional.of(0).ifPresent(new Consumer() { 130 | @Override 131 | public void accept(Object o) { 132 | value[0] = 1; 133 | } 134 | }); 135 | Assert.assertEquals(1, value[0]); 136 | } 137 | 138 | @Test 139 | public void ifPresentOrElseDoesActionWhenPresent() { 140 | final int[] value = {0}; 141 | Optional.of(0).ifPresentOrElse(new Consumer() { 142 | @Override 143 | public void accept(Integer o) { 144 | value[0] = 1; 145 | } 146 | }, new Runnable() { 147 | @Override 148 | public void run() { 149 | } 150 | }); 151 | Assert.assertEquals(1, value[0]); 152 | } 153 | 154 | @Test 155 | public void ifPresentOrElseDoesEmptyActionWhenEmpty() { 156 | final int[] value = {0}; 157 | Optional.empty().ifPresentOrElse(new Consumer() { 158 | @Override 159 | public void accept(Object o) { 160 | } 161 | }, new Runnable() { 162 | @Override 163 | public void run() { 164 | value[0] = 1; 165 | } 166 | }); 167 | Assert.assertEquals(1, value[0]); 168 | } 169 | 170 | @Test 171 | public void isPresentOfEmptyReturnsFalse() { 172 | Assert.assertFalse(Optional.empty().isPresent()); 173 | } 174 | 175 | @Test 176 | public void isPresentOfValueReturnsTrue() { 177 | Assert.assertTrue(Optional.of(0).isPresent()); 178 | } 179 | 180 | @Test 181 | public void mapOfEmptyReturnsEmpty() { 182 | Optional empty = Optional.empty(); 183 | Optional mapped = empty.map(new Function() { 184 | @Override 185 | public String apply(Integer integer) { 186 | return "mapped"; 187 | } 188 | }); 189 | Assert.assertEquals(Optional.empty(), mapped); 190 | } 191 | 192 | @Test 193 | public void mapOfValueReturnsMappedValue() { 194 | Optional mapped = Optional.of(0).map(new Function() { 195 | @Override 196 | public String apply(Integer integer) { 197 | return "mapped"; 198 | } 199 | }); 200 | Assert.assertEquals(Optional.of("mapped"), mapped); 201 | } 202 | 203 | @Test 204 | public void orReturnsThisWhenPresent() { 205 | Optional actual = Optional.of(0).or(new Supplier>() { 206 | @Override 207 | public Optional get() { 208 | return Optional.of(1); 209 | } 210 | }); 211 | Assert.assertEquals(Optional.of(0), actual); 212 | } 213 | 214 | @Test 215 | public void orReturnsSuppliedWhenEmpty() { 216 | Optional actual = Optional.empty().or(new Supplier>() { 217 | @Override 218 | public Optional get() { 219 | return Optional.of(1); 220 | } 221 | }); 222 | Assert.assertEquals(Optional.of(1), actual); 223 | } 224 | 225 | @Test(expected = NullPointerException.class) 226 | public void orThrowsNPEOnNullSupplier() { 227 | Optional.empty().or(null); 228 | } 229 | 230 | @Test(expected = NullPointerException.class) 231 | public void orThrowsNPEOnNullSupplied() { 232 | Optional.empty().or(new Supplier>() { 233 | @Override 234 | public Optional get() { 235 | return null; 236 | } 237 | }); 238 | } 239 | 240 | @Test 241 | public void orElseOfEmptyReturnsElse() { 242 | Assert.assertEquals("else", Optional.empty().orElse("else")); 243 | } 244 | 245 | @Test 246 | public void orElseOfValueReturnsValue() { 247 | Assert.assertEquals("value", Optional.of("value").orElse("else")); 248 | } 249 | 250 | 251 | @Test 252 | public void orElseGetOfEmptyReturnsElse() { 253 | String actual = Optional.empty().orElseGet(new Supplier() { 254 | @Override 255 | public String get() { 256 | return "else"; 257 | } 258 | }); 259 | Assert.assertEquals("else", actual); 260 | } 261 | 262 | @Test 263 | public void orElseGetOfValueReturnsValue() { 264 | String actual = Optional.of("value").orElseGet(new Supplier() { 265 | @Override 266 | public String get() { 267 | return "else"; 268 | } 269 | }); 270 | Assert.assertEquals("value", actual); 271 | } 272 | 273 | @Test 274 | public void orElseThrowOfEmptyThrowsException() throws Exception { 275 | final Exception exception = new Exception(); 276 | try { 277 | String actual = Optional.empty().orElseThrow(new Supplier() { 278 | @Override 279 | public Exception get() { 280 | return exception; 281 | } 282 | }); 283 | Assert.fail(); 284 | Assert.assertEquals("value", actual); 285 | } catch (Exception e) { 286 | Assert.assertEquals(exception, e); 287 | } 288 | } 289 | 290 | @Test 291 | public void orElseThrowOfValueReturnsValue() throws Exception { 292 | String actual = Optional.of("value").orElseThrow(new Supplier() { 293 | @Override 294 | public Exception get() { 295 | return new Exception(); 296 | } 297 | }); 298 | Assert.assertEquals("value", actual); 299 | } 300 | 301 | @Test 302 | public void equalsOfValueDoesNotEqualsAnother() throws Exception { 303 | Assert.assertNotEquals(Optional.of(1), Optional.of(2)); 304 | } 305 | 306 | @Test 307 | public void equalsOfValueEqualsItself() throws Exception { 308 | Assert.assertEquals(Optional.of(1), Optional.of(1)); 309 | } 310 | 311 | @Test 312 | public void equalsOfValueDoesNotEqualDifferentType() throws Exception { 313 | Assert.assertNotEquals(Optional.of(1), "a"); 314 | } 315 | 316 | @Test 317 | public void equalsOfEmptyDoesNotEqualValue() throws Exception { 318 | Assert.assertNotEquals(Optional.empty(), Optional.of(1)); 319 | } 320 | 321 | @Test 322 | public void hashCodeOfEmptyIsZero() { 323 | Assert.assertEquals(0, Optional.empty().hashCode()); 324 | } 325 | 326 | @Test 327 | public void hashCodeOfValueIsValuesHashCode() { 328 | Assert.assertEquals("hash".hashCode(), Optional.of("hash").hashCode()); 329 | } 330 | 331 | @Test 332 | public void toStringOfEmpty() { 333 | Assert.assertEquals("Optional.empty", Optional.empty().toString()); 334 | } 335 | 336 | @Test 337 | public void toStringOfValue() { 338 | Assert.assertEquals("Optional[0]", Optional.of(0).toString()); 339 | } 340 | } 341 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /lib/src/main/java/com/github/dmstocking/optional/java/util/Optional.java: -------------------------------------------------------------------------------- 1 | package com.github.dmstocking.optional.java.util; 2 | 3 | import com.github.dmstocking.optional.java.util.function.Consumer; 4 | import com.github.dmstocking.optional.java.util.function.Function; 5 | import com.github.dmstocking.optional.java.util.function.Predicate; 6 | import com.github.dmstocking.optional.java.util.function.Supplier; 7 | 8 | import java.util.NoSuchElementException; 9 | 10 | /** 11 | * A container object which may or may not contain a non-null value. If a value is present, {@code 12 | * isPresent()} will return {@code true} and {@code get()} will return the value. 13 | * 14 | * Additional methods that depend on the presence or absence of a contained value are provided, such 15 | * as {@code orElse()} (return a default value if value not present) and {@code ifPresent()} 16 | * (execute a block of code if the value is present). 17 | */ 18 | @SuppressWarnings("WeakerAccess") 19 | public final class Optional { 20 | 21 | @SuppressWarnings("unchecked") 22 | private static final Optional EMPTY = new Optional(null); 23 | 24 | /** 25 | * Returns an empty {@code Optional} instance. No value is present for this Optional. 26 | * 27 | * Though it may be tempting to do so, avoid testing if an object is empty by comparing with 28 | * {@code ==} against instances returned by {@code Optional.empty()}. There is no guarantee that 29 | * it is a singleton. Instead, use {@link #isPresent()} 30 | * 31 | * @param Type of the non-existent value 32 | * @return an empty {@code Optional} 33 | */ 34 | @SuppressWarnings("unchecked") 35 | public static Optional empty() { 36 | return (Optional) EMPTY; 37 | } 38 | 39 | private final T value; 40 | 41 | private Optional(T value) { 42 | this.value = value; 43 | } 44 | 45 | /** 46 | * Returns an Optional with the specified present non-null value. 47 | * 48 | * @param value the value to be present, which must be non-null 49 | * @param the class of the value 50 | * @return an Optional with the value present 51 | * @throws NullPointerException if value is null 52 | */ 53 | public static Optional of(T value) { 54 | if (value == null) { 55 | throw new NullPointerException(); 56 | } 57 | 58 | return new Optional(value); 59 | } 60 | 61 | /** 62 | * Returns an Optional describing the specified value, if non-null otherwise returns an empty 63 | * Optional. 64 | * 65 | * @param value the possible-null value to describe 66 | * @param the class of the value 67 | * @return an Optional with a present value if the specified value is non-null, otherwise an 68 | * empty Optional 69 | */ 70 | public static Optional ofNullable(T value) { 71 | if (value != null) { 72 | return new Optional(value); 73 | } 74 | 75 | return empty(); 76 | } 77 | 78 | /** 79 | * If a value is present, and the value matches the given predicate, return an {@code Optional} 80 | * describing the value, otherwise return an empty {@code Optional}. 81 | * 82 | * @param predicate a predicate to apply to the value, if present 83 | * @return an Optional describing the value of this {@code Optional} if a value is present and 84 | * the value matches the given predicate, otherwise an empty {@code Optional}. 85 | * @throws NullPointerException if the predicate is null 86 | */ 87 | public Optional filter(Predicate predicate) { 88 | if (isPresent() && predicate.test(value)) { 89 | return this; 90 | } 91 | 92 | return empty(); 93 | } 94 | 95 | /** 96 | * If a value is present, apply the provided {@code Optional}-bearing mapping function to it, 97 | * return that result, otherwise return an empty {@code Optional}. This method is similar to 98 | * {@link #map(Function)}, but the provided mapper is one whose result is already an {@code 99 | * Optional}, and if invoked, {@code flatMap} does not wrap it with an additional {@code 100 | * Optional}. 101 | * 102 | * @param The type parameter to the {@code Optional} returned by 103 | * @param mapper a mapping function to apply to the value, if present the mapping function 104 | * @return the result of applying an {@code Optional}-bearing mapping function to the value of 105 | * this {@code Optional}, if a value is present, otherwise an empty {@code Optional} 106 | * @throws NullPointerException if the mapping function is null or returns a null result 107 | */ 108 | public Optional flatMap(Function> mapper) { 109 | if (isPresent()) { 110 | return mapper.apply(value); 111 | } 112 | 113 | return empty(); 114 | } 115 | 116 | /** 117 | * If a value is present in this {@code Optional}, returns the value, otherwise throws {@code 118 | * NoSuchElementException}. 119 | * 120 | * @return the non-null value held by this {@code Optional} 121 | * @throws NoSuchElementException if there is no value present 122 | * @see Optional#isPresent() 123 | */ 124 | public T get() { 125 | if (isPresent()) { 126 | return value; 127 | } 128 | 129 | throw new NoSuchElementException("No value present"); 130 | } 131 | 132 | /** 133 | * If a value is present, invoke the specified consumer with the value, otherwise do nothing. 134 | * 135 | * @param consumer block to be executed if a value is present 136 | * @throws NullPointerException if value is present and {@code consumer} is null 137 | */ 138 | public void ifPresent(Consumer consumer) { 139 | if (isPresent()) { 140 | consumer.accept(value); 141 | } 142 | } 143 | 144 | /** 145 | * If a value is present, invoke the specified consumer with the value, otherwise performs the 146 | * given empty-based aciton. 147 | * 148 | * @param consumer block to be executed if a value is present 149 | * @param emptyAction the empty-based action to be performed, if no value is present 150 | * @throws NullPointerException if value is present and {@code consumer} is null, or no value is 151 | * present and the given empty-based action is null. 152 | */ 153 | public void ifPresentOrElse(Consumer consumer, Runnable emptyAction) { 154 | if (isPresent()) { 155 | consumer.accept(value); 156 | } else { 157 | emptyAction.run(); 158 | } 159 | } 160 | 161 | public boolean isPresent() { 162 | return value != null; 163 | } 164 | 165 | /** 166 | * If a value is present, apply the provided mapping function to it, and if the result is 167 | * non-null, return an {@code Optional} describing the result. Otherwise return an empty {@code 168 | * Optional}.

This method supports post-processing on optional values, without the need to 169 | * explicitly check for a return status. For example, the following code traverses a stream of 170 | * file names, selects one that has not yet been processed, and then opens that file, returning 171 | * an {@code Optional}: 172 | * 173 | *

{@code
174 |      *     Optional fis =
175 |      *         names.stream().filter(name -> !isProcessedYet(name))
176 |      *                       .findFirst()
177 |      *                       .map(name -> new FileInputStream(name));
178 |      * }
179 | * 180 | * Here, {@code findFirst} returns an {@code Optional}, and then {@code map} returns an 181 | * {@code Optional} for the desired file if one exists.

182 | * 183 | * @param The type of the result of the mapping function 184 | * @param mapper a mapping function to apply to the value, if present 185 | * @return an {@code Optional} describing the result of applying a mapping function to the value 186 | * of this {@code Optional}, if a value is present, otherwise an empty {@code Optional} 187 | * @throws NullPointerException if the mapping function is null 188 | */ 189 | public Optional map(Function mapper) { 190 | if (isPresent()) { 191 | return Optional.ofNullable(mapper.apply(value)); 192 | } 193 | 194 | return empty(); 195 | } 196 | 197 | /** 198 | * If a value is present, returns an Optional describing the value, otherwise returns an 199 | * Optional produced by the supplying function. 200 | * 201 | * @param supplier the supplying function that produces an Optional to be returned 202 | * @return returns an Optional describing the value of this Optional, if a value is present, 203 | * otherwise an Optional produced by the supplying function. 204 | */ 205 | public Optional or(Supplier> supplier) { 206 | if (isPresent()) { 207 | return this; 208 | } 209 | 210 | if (supplier == null) { 211 | throw new NullPointerException(); 212 | } 213 | 214 | Optional optional = (Optional) supplier.get(); 215 | if (optional == null) { 216 | throw new NullPointerException(); 217 | } 218 | 219 | return optional; 220 | } 221 | 222 | /** 223 | * Return the value if present, otherwise return {@code other}. 224 | * 225 | * @param other the value to be returned if there is no value present, may be null 226 | * @return the value, if present, otherwise {@code other} 227 | */ 228 | public T orElse(T other) { 229 | if (isPresent()) { 230 | return value; 231 | } 232 | 233 | return other; 234 | } 235 | 236 | /** 237 | * Return the value if present, otherwise invoke {@code other} and return the result of that 238 | * invocation. 239 | * 240 | * @param other a {@code Supplier} whose result is returned if no value is present 241 | * @return the value if present otherwise the result of {@code other.get()} 242 | * @throws NullPointerException if value is not present and {@code other} is null 243 | */ 244 | public T orElseGet(Supplier other) { 245 | if (isPresent()) { 246 | return value; 247 | } 248 | 249 | return other.get(); 250 | } 251 | 252 | /** 253 | * Return the contained value, if present, otherwise throw an exception to be created by the 254 | * provided supplier. 255 | * 256 | *

A method reference to the exception constructor with an empty argument list can be used 257 | * as the supplier. For example, {@code IllegalStateException::new}

258 | * 259 | * @param Type of the exception to be thrown 260 | * @param exceptionSupplier The supplier which will return the exception to be thrown 261 | * @return the present value 262 | * @throws X if there is no value present 263 | * @throws NullPointerException if no value is present and {@code exceptionSupplier} is null 264 | */ 265 | public T orElseThrow(Supplier exceptionSupplier) throws X { 266 | if (isPresent()) { 267 | return value; 268 | } 269 | 270 | throw exceptionSupplier.get(); 271 | } 272 | 273 | /** 274 | * Indicates whether some other object is "equal to" this Optional. The other object is 275 | * considered equal if:
  • it is also an {@code Optional} and;
  • both instances have no 276 | * value present or;
  • the present values are "equal to" each other via {@code equals()}. 277 | *
278 | * 279 | * @param o an object to be tested for equality 280 | * @return {code true} if the other object is "equal to" this object otherwise {@code false} 281 | */ 282 | @Override 283 | public boolean equals(Object o) { 284 | if (this == o) { 285 | return true; 286 | } 287 | 288 | if (!(o instanceof Optional)) { 289 | return false; 290 | } 291 | 292 | if (isPresent()) { 293 | Optional other = (Optional) o; 294 | return value.equals(other.value); 295 | } 296 | 297 | return false; 298 | } 299 | 300 | /** 301 | * Returns the hash code value of the present value, if any, or 0 (zero) if no value is 302 | * present. 303 | * 304 | * @return hash code value of the present value or 0 if no value is present 305 | */ 306 | @Override 307 | public int hashCode() { 308 | if (isPresent()) { 309 | return value.hashCode(); 310 | } 311 | 312 | return 0; 313 | } 314 | 315 | /** 316 | * Returns a non-empty string representation of this Optional suitable for debugging. The exact 317 | * presentation format is unspecified and may vary between implementations and versions. 318 | * 319 | *

If a value is present the result must include its string representation in the result. 320 | * Empty and present Optionals must be unambiguously differentiable.

321 | * 322 | * @return the string representation of this instance 323 | */ 324 | @Override 325 | public String toString() { 326 | if (isPresent()) { 327 | return "Optional[" + value.toString() + "]"; 328 | } 329 | 330 | return "Optional.empty"; 331 | } 332 | } 333 | --------------------------------------------------------------------------------