Skip to content

Instantly share code, notes, and snippets.

@Aayush-Aggarwal

Aayush-Aggarwal/Demo

Last active Mar 8, 2018
Embed
What would you like to do?
Demo for optional methods.
import java.util.Optional;
public class Demo {
class Person {
private String name = "Hello To Optional";
public Optional<String> getName() {
return Optional.ofNullable(name);
}
}
public void optionalMethodDemo() {
Person person = new Person();
/**
* of() Example
*/
Optional<Person> personOptional = Optional.of(person);
/**
* ofNullable() Example
*/
Optional<String> dataWithNull = Optional.ofNullable(null);
/**
* empty() Example
* Also (emptyOptional.get();)this will throw an Exception as get() only deal with value.
* Not with empty Optional object.
*/
Optional<String> emptyOptional = Optional.empty();
// emptyOptional.get();
/**
* map() Example
*/
Optional<Optional<String>> wrapper = personOptional.map(Person::getName);
Optional<String> nameOptional = wrapper.orElseThrow(IllegalArgumentException::new);
String name1 = nameOptional.orElse("");
System.out.println("name1 :: " + name1);
/**
* flatMap() Example
*/
String name = personOptional.flatMap(Person::getName).orElse("");
System.out.println("name :: " + name);
/**
* isPresent() Example
*/
if(personOptional.isPresent()){
System.out.println("The Data isPresent :: " + personOptional);
System.out.println("The Data isPresent and the data is :: " + personOptional.orElse(person).name);
}
/**
* ifPresent() Example
*/
personOptional.ifPresent(data -> System.out.println(personOptional.orElse(person).name));
/**
* filter() Example
*/
Optional<Person> filterValue = personOptional.filter(data -> data.name.equals("Hello To Optional"));
System.out.println("Filter value :: " + filterValue);
/**
* orElse() Example
*/
String value = personOptional.orElse(person).name ;
System.out.println("value :: " + value) ;
/**
* orElseGet() Example
*/
String invokedValue = personOptional.orElseGet(() -> person).name ;
System.out.println("invokedValue :: " + invokedValue);
/**
* equals() Example
*/
Optional<String> data1 = Optional.of("knoldus");
Optional<String> data2 = Optional.of("knoldus");
System.out.println(data1.equals(data2)); // true
System.out.println(data1 == data2); // false
Optional<String> data1 = Optional.empty();
Optional<String> data2 = Optional.empty();
System.out.println(data1.equals(data2)); // true
System.out.println(data1 == data2); // true
/**
* orElseThrow() Example
*/
String notNullValue = personOptional.orElseThrow(IllegalArgumentException::new).name;
String nullValue = dataWithNull.orElseThrow(IllegalArgumentException::new); //throw IllegalArgumentException
System.out.println(notNullValue);
System.out.println(nullValue);
}
public static void main(String []args){
Demo demo = new Demo();
demo.optionalMethodDemo();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.