Java Login

About javalogin.com

Hello guys,
javalogin.com is for Java and J2EE developers, all examples are simple and easy to understand 

It is developed and maintained by Vaibhav Sharma. The views expressed on this website are his own and do not necessarily reflect the views of his former, current or future employers. I am professional Web development. I work for an IT company as Senior Consultant. Primary I write about spring, hibernate and web-services. I am trying to present here new technologies.


     << Previous
Next >>     


Optional Class


Java 8 comes with the Optional class in the java.util package for avoiding null return values (and thus NullPointerException). The null reference is a very common problem in Java, everybody got once a NullPointerException because some variable or input parameter was not properly validated. In Java, null, can have a logical value and a meaning; so it is important to take it into consideration and do not ignore it.
Some points about Optional class.

  • The Optional class is a container object which may or may not contains a non-null value.
  • Optional class has orElseThrow() method to throw an exception if a value is not present.
  • Optional.isPresent() method will return true, if a non-value is available and get() method of Optional class will return that value.
  • The java.util.Optional class is a value-based class and use of identity sensitive operations e.g. using the == operator, calling identityHashCode() and synchronization should be avoided on an Optional object.
  • You can also use the orElseThrow() method to throw an exception if a value is not present.
  • If value is not present in Optional class object, you can call Optional.orElse() to return a default value.
  • You can use the map() method to transform the value contained in the Optional object and you can also use the filter() method to weed out any unwanted value from the Optional object
  • Optional also provides filter(), map(), and flatMap() method to write safe code in Java 8 functional style. The method behaves similarly as they do in Stream class, so if you have used them before, you can use them in the same way with the Optional class as well.
  • You can create Optional using the static factory method Optional.of(non-null-value) which takes a non-null value and wrap it with Optional. It will throw NullPointerException if the value is null. Similarly, the Optional.isEmpty() method return an empty instance of Optional class in Java.
  • Optional improves the readability and convey information which fields are optional.

Example of Optional


Origin.java

class Origin {
private String name;

public Origin(String name) {
this.name = name;
}

public String getName() {
return name;
}

public Optional<Vegetable> growIntoVegetable() {
return Optional.of(new Vegetable(this));
}

public Optional<Vegetable> growIntoVegetable(Integer price) {
return Optional.of(new Vegetable(this, price));
}
}


Vegetable.java

class Vegetable {
private Origin origin;
private Optional<Integer> optionalPrice;

public Vegetable(Origin origin) {
this.origin = origin;
this.optionalPrice = Optional.empty();
}

public Vegetable(String name, Integer price) {
this.origin = new Origin(name);
this.optionalPrice = Optional.of(price);
}

public Vegetable(Origin origin, Integer price) {
this.origin = origin;
this.optionalPrice = Optional.of(price);
}

public Optional<Integer> getPrice() {
return optionalPrice;
}

public void eat() {
System.out.println("Found " + origin.getName() + ", let's eat...");
}

public Origin getOrigin() {
return origin;
}

public void setPrice(int price) {
optionalPrice = Optional.of(price);
}
}

OptionalTest.java

import java.util.Arrays;
import java.util.Optional;

public class OptionalTest {

public static void main(String[] args) {
Optional<Origin> emptyOrigin = Optional.empty();
System.out.println("Is Origin empty? " + !emptyOrigin.isPresent());

Optional<Origin> okraOrigin = Optional.of(new Origin("okra Origin"));
System.out.println("Does okra origin exists? "
+ okraOrigin.isPresent());

Integer price = okraOrigin.flatMap(Origin::growIntoVegetable)
.flatMap(Vegetable::getPrice).orElse(100);
System.out.println("Price of okra is " + price);

price = okraOrigin.flatMap(origin -> origin.growIntoVegetable(200))
.flatMap(Vegetable::getPrice).orElse(100);
System.out.println("Price of okra is " + price);

Vegetable[] vegetables = { new Vegetable("okrae", 80),
new Vegetable("Apple", 100), new Vegetable("Orange", 80) };
System.out.println("Find vegetables for a price less than 20,
shouldn't be able to find any");
Optional<Vegetable> optional = Arrays.stream(vegetables).filter(f ->
f.getPrice().get() < 20).findAny();
System.out.println("Got any? " + optional.isPresent());

try {
optional.get();
} catch (java.util.NoSuchElementException e) {
System.out.println("If there is no vegetable found, optional.get() throws NoSuchElementException");
}
System.out.println("Find vegetables for a price less than 200");

Arrays.stream(vegetables).filter(f ->
f.getPrice().get() < 200).findFirst().ifPresent(f -> f.eat());
}
}



     << Previous
Next >>