0% found this document useful (0 votes)
24 views

Java 8 - Part2 Optional Class

Uploaded by

amaleshmsc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Java 8 - Part2 Optional Class

Uploaded by

amaleshmsc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Java Optional Class

Java introduced a new class Optional in jdk8. It is a public final class and
used to deal with NullPointerException in Java application. You must import
java.util package to use this class. It provides methods which are used to
check the presence of value for particular variable.
/*ispresent()
* isempty()
* ifpresent()
* orElse()
* orElseget()
* get()
* orElseThrow()
*/

Java Optional Class Methods


Methods Description

public static <T> Optional<T> It returns an empty Optional object. No value is


empty() present for this Optional.

public static <T> Optional<T> of(T It returns an Optional with the specified present
value) non-null value.

public static <T> Optional<T> It returns an Optional describing the specified


ofNullable(T value) value, if non-null, otherwise returns an empty
Optional.

public T get() If a value is present in this Optional, returns the


value, otherwise throws
NoSuchElementException.

public boolean isPresent() It returns true if there is a value present,


otherwise false.

public void ifPresent(Consumer<? If a value is present, invoke the specified


super T> consumer) consumer with the value, otherwise do nothing.
public Optional<T> If a value is present, and the value matches the
filter(Predicate<? super T> given predicate, return an Optional describing
predicate) the value, otherwise return an empty Optional.

public <U> Optional<U> If a value is present, apply the provided


map(Function<? super T,? extends mapping function to it, and if the result is non-
U> mapper) null, return an Optional describing the result.
Otherwise return an empty Optional.

public <U> Optional<U> If a value is present, apply the provided


flatMap(Function<? super Optional-bearing mapping function to it, return
T,Optional<U> mapper) that result, otherwise return an empty Optional.

public T orElse(T other) It returns the value if present, otherwise returns


other.

public T orElseGet(Supplier<? It returns the value if present, otherwise invoke


extends T> other) other and return the result of that invocation.

public <X extends Throwable> T It returns the contained value, if present,


orElseThrow(Supplier<? extends otherwise throw an exception to be created by
X> exceptionSupplier) throws X the provided supplier.
extends Throwable

public boolean equals(Object obj) Indicates whether some other object is "equal
to" this Optional or not. The other object is
considered equal if:
o It is also an Optional and;
o Both instances have no value present or;
o the present values are "equal to" each
other via equals().

public int hashCode() It returns the hash code value of the present
value, if any, or returns 0 (zero) if no value is
present.

public String toString() It returns a non-empty string representation of


this Optional suitable for debugging. The exact
presentation format is unspecified and may
vary between implementations and versions.

Example: Java Program without using Optional


In the following example, we are not using Optional class. This program
terminates abnormally and throws a nullPointerException.
1. public class OptionalExample {
2. public static void main(String[] args) {
3. String[] str = new String[10];
4. String lowercaseString = str[5].toLowerCase();
5. System.out.print(lowercaseString);
6. }
7. }
Output:
Exception in thread "main" java.lang.NullPointerException
at lambdaExample.OptionalExample.main(OptionalExample.java:6)
To avoid the abnormal termination, we use Optional class. In the following
example, we are using Optional. So, our program can execute without
crashing.
Java Optional Example: If Value is not Present
1. import java.util.Optional;
2. public class OptionalExample {
3. public static void main(String[] args) {
4. String[] str = new String[10];
5. Optional<String> checkNull = Optional.ofNullable(str[5]);
6. if(checkNull.isPresent()){ // check for value is present or not
7. String lowercaseString = str[5].toLowerCase();
8. System.out.print(lowercaseString);
9. }else
10. System.out.println("string value is not present");
11. }
12. }
Output:
string value is not present

Java Optional Example: If Value is Present


1. import java.util.Optional;
2. public class OptionalExample {
3. public static void main(String[] args) {
4. String[] str = new String[10];
5. str[5] = "JAVA OPTIONAL CLASS EXAMPLE";// Setting value for 5th index
6. Optional<String> checkNull = Optional.ofNullable(str[5]);
7. if(checkNull.isPresent()){ // It Checks, value is present or not
8. String lowercaseString = str[5].toLowerCase();
9. System.out.print(lowercaseString);
10. }else
11. System.out.println("String value is not present");
12. }
13. }
Output:
java optional class example

Another Java Optional Example


1. import java.util.Optional;
2. public class OptionalExample {
3. public static void main(String[] args) {
4. str[5] = "JAVA OPTIONAL CLASS EXAMPLE"; // Setting value for 5th inde
x
5. String[] str = new String[10];
6.
7. Optional<String> checkNull = Optional.ofNullable(str[5]);
8. checkNull.ifPresent(System.out::println); // printing value by using met
hod reference
9. System.out.println(checkNull.get()); // printing value by using get met
hod
10. System.out.println(str[5].toLowerCase());
11. }
12. }
Output:
JAVA OPTIONAL CLASS EXAMPLE
JAVA OPTIONAL CLASS EXAMPLE
java optional class example

Java Optional Methods Example


1. import java.util.Optional;
2. public class OptionalExample {
3. public static void main(String[] args) {
4. String[] str = new String[10];
5. str[5] = "JAVA OPTIONAL CLASS EXAMPLE"; // Setting value for 5th inde
x
6. // It returns an empty instance of Optional class
7. Optional<String> empty = Optional.empty();
8. System.out.println(empty);
9. // It returns a non-empty Optional
10. Optional<String> value = Optional.of(str[5]);
11. // If value is present, it returns an Optional otherwise returns an e
mpty Optional
12. System.out.println("Filtered value: "+value.filter((s)-
>s.equals("Abc")));
13. System.out.println("Filtered value: "+value.filter((s)-
>s.equals("JAVA OPTIONAL CLASS EXAMPLE")));
14. // It returns value of an Optional. if value is not present, it throws
an NoSuchElementException
15. System.out.println("Getting value: "+value.get());
16. // It returns hashCode of the value
17. System.out.println("Getting hashCode: "+value.hashCode());
18. // It returns true if value is present, otherwise false
19. System.out.println("Is value present: "+value.isPresent());
20. // It returns non-empty Optional if value is present, otherwise retu
rns an empty Optional
21. System.out.println("Nullable Optional: "+Optional.ofNullable(str[5]
));
22. // It returns value if available, otherwise returns specified value,
23. System.out.println("orElse: "+value.orElse("Value is not present"))
;
24. System.out.println("orElse: "+empty.orElse("Value is not present")
);
25. value.ifPresent(System.out::println); // printing value by using m
ethod reference
26. }
27. }
Output:
Optional.empty
Filtered value: Optional.empty
Filtered value: Optional[JAVA OPTIONAL CLASS EXAMPLE]
Getting value: JAVA OPTIONAL CLASS EXAMPLE
Getting hashCode: -619947648
Is value present: true
Nullable Optional: Optional[JAVA OPTIONAL CLASS EXAMPLE]
orElse: JAVA OPTIONAL CLASS EXAMPLE
orElse: Value is not present
JAVA OPTIONAL CLASS EXAMPLE

Sample Program:

import java.util.Optional;
public class OptionalMethods {
static void print() {
System.out.println("welcomes you");
}
static String Name() {
return "i am orelseget() method call";
}
public static void main(String[] args) {
/*ispresent()
* isempty()
* ifpresent()
* orElse()
* get()
* orElseget()
* orElseThrow()
*/
Optional<String> obj=Optional.of("a");
System.out.println("ispresent o/p "+obj.isPresent());//true

String s="ranjima";
Optional<String> obj1=Optional.ofNullable(s);
System.out.println(obj1.isPresent());
System.out.println("isempty result "+obj1.isEmpty());

//ifpresent()
obj1.ifPresent(str->System.out.println(str.length()));
obj1.ifPresent(str->OptionalMethods.print());

//orElse()
String place=null;//string
Optional<String> ref=Optional.ofNullable(place);//string value will be replaced
System.out.println(ref.orElse("tamilnadu"));

//get();
System.out.println(obj);//Optional[a]
System.out.println(obj.get());//a

//orElseget()
String name=null;
Optional<String> st=Optional.ofNullable(name);
System.out.println(st.orElseGet(()->OptionalMethods.Name()));
Optional op=Optional.ofNullable(null);
System.out.println(op);
//Optional.empty
//orelsethrow

try {
st.orElseThrow(()->new Exception("please check the value is present"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Optional val=Optional.of("ranjini");
System.out.println(val);
System.out.println(val.get());
}
}

You might also like