Optional in java 8

  1. Java 8 Optional Class
  2. Understanding, Accepting and Leveraging Optional in Java
  3. The Java 8 Stream API Tutorial
  4. Java 8 Optional (with Examples)
  5. Filtering a Stream of Optionals in Java


Download: Optional in java 8
Size: 42.45 MB

Java 8 Optional Class

In Java 8, we have a newly introduced Optional class in java.util package. This class is introduced to avoid NullPointerException that we frequently encounters if we do not perform null checks in our code. Using this class we can easily check whether a variable has null value or not and by doing this we can avoid the NullPointerException. In this guide, we will see how to work with Optional class and the usage of various methods of this class. Before we see the example of Optional class, lets see what happens when we don’t use Optional class and do not perform null check. Java Example: Without using Optional class In this example, we didn’t assign the value to the String str and we are trying to get the public class Example Output: Optional.empty Optional[Game of Thrones] References:

Understanding, Accepting and Leveraging Optional in Java

By: Eugen| September 14, 2017 Overview One of the most interesting features that Java 8 introduces to the language is the new Optional class. The main issue this class is intended to tackle is the infamous NullPointerExceptionthat every Essentially, this is a wrapper class that contains an optional value, meaning it can either contain an object or it can simply be empty. Optional comes along with a strong move towards functional programming in Javaand is meant to help in that paradigm, but definitely also outside of that. Let’s start with a simple use-case. Before Java 8, any number of operations involving accessing an object’s methods or properties could result in a NullPointerException: String isocode = user.getAddress().getCountry().getIsocode().toUpperCase(); If we wanted to make sure we won’t hit the exception in this short example, we would need to do explicit checks for every value before accessing it: if (user != null) Conclusion Optional is a useful addition to the Java language, intended to minimize the number of NullPointerExceptions in your code, though not able to completely remove them. It’s also a well designed and very natural addition to the new functional support added in Java 8. Overall, this simple yet powerful class helps create code that’s, simply put, more readable and less error-prone than its procedural counterpart. Interested in continuously improving your Java application? Improve Your Code with Retrace APM Stackify's APM tools are used by thous...

The Java 8 Stream API Tutorial

In this comprehensive tutorial, we'll go through the practical uses of Java 8 Streams from creation to parallel execution. To understand this material, readers need to have a basic knowledge of Java 8 (lambda expressions, Optional, method references) and of the Stream API. In order to be more familiar with these topics, please take a look at our previous articles: An array can also be the source of a stream: Stream streamOfArray = Stream.of("a", "b", "c"); We can also create a stream out of an existing array or of part of an array: String[] arr = new String[]; Stream streamOfArrayFull = Arrays.stream(arr); Stream streamOfArrayPart = Arrays.stream(arr, 1, 3); 2.4. Stream.builder() Another way of creating an infinite stream is by using the iterate() method: Stream streamIterated = Stream.iterate(40, n -> n + 2).limit(20); The first element of the resulting stream is the first parameter of the iterate() method. When creating every following element, the specified function is applied to the previous element. In the example above the second element will be 42. 2.7. Stream of Primitives Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream. Using the new interfaces alleviates unnecessary auto-boxing, which allows for increased productivity: IntStream ...

Java 8 Optional (with Examples)

All of us must have encountered NullPointerException in our applications. It happens when you try to use an object that has not been initialized, initialized with null or does not point to any instance. In simple words, NULL simply means ‘absence of a value’. In this Java tutorial, we will discuss one of null is used. 1. What is the Type of null? In Java, we use a reference type to gain access to an object, and when we don’t have a specific object to make our reference point to, then we set such references to null to imply the absence of a value. The use of null is so common that we rarely put more thought into it. For example, field members of objects are automatically initialized to null, and programmers typically initialize reference types to null when they don’t have an initial value to give them. In general, null is used everytime where we don’t know, or we don’t have a value to give to a reference. In Java null is actually a type, a special one. It has no name so we cannot declare variables of its type or cast any variables to it; in fact there is only a single value that can be associated with it (i.e. the literal null). Remember that unlike any other types in Java, a null reference can be safely assigned to any other reference types without any error (See 2. Problems when using null? Generally, the API designers put the descriptive java docs in APIs and mention there that API can return a null value. The problem is that the caller of the API might have missed readi...

Filtering a Stream of Optionals in Java

In this article, we're going to talk about how to filter out non-empty values from a Stream of Optionals. We'll be looking at three different approaches – two using Java 8 and one using the new support in Java 9. We will be working on the same list in all examples: List> listOfOptionals = Arrays.asList( Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar")); 2. Using filter() One of the options in Java 8 is to filter out the values with Optional::isPresent and then perform mapping with the Optional::get function to extract values: List filteredList = listOfOptionals.stream() .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); 3. Using flatMap() List filteredList = listOfOptionals.stream() .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) .collect(Collectors.toList()); Alternatively, you could apply the same approach using a different way of converting an Optional to Stream: List filteredList = listOfOptionals.stream() .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) .collect(Collectors.toList()); 4. Java 9's Optional::stream All this will get quite simplified with the arrival of Java 9 that adds a stream() method to Optional. This approach is similar to the one showed in section 3 but this time we are using a predefined method for converting Optional instance into a Stream instance: It will return a stream of either one or zero element(s) whether the Optional value is or isn't present: List filtered...