Tuesday, April 14, 2020

Java 8 flatMap Examples - Stream flatmap convert Stream<List<List<String>>> into Stream<String>

1. Introduction


In this article, We'll learn about java 8 new Stream API flatMap() method. When to use it and how to use it.

flatMap() method is used to convert or flatten Stream of collections into Stream of collection values by removing the collection.

Removing collection such as List or Set from Stream is called flattening.

FlatMap() is part of Stream Intermediate Operations in Java 8.

Java 8, Stream can hold any type of collections and can be converted into Stream<T> as below.

Stream<List<List<String>>> --> apply flatMap() logic --> Stream<String>
Stream<Set<Set<String>>> --> apply flatMap() logic --> Stream<String>
Stream<List<String>>> --> apply flatMap() logic --> Stream<String>
Stream<List<Object>>> --> apply flatMap() logic --> Stream<Object>


Sunday, April 12, 2020

Java 8 Optional orElseThrow() Example | Throw Exception in Optional in Java 8

1. introduction


In this tutorial, We'll learn how to throw an exception if the option is empty. Optional API orElseThrow() method returns value from Optional if present. Otherwise, it will throw the exception created by the Supplier.

2. Syntax


public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
                                    throws X extends Throwable


Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.

A method reference to the exception constructor with an empty argument list can be used as the supplier. For example, IllegalStateException::new, ArithmeticException::new

Java 8 Optional orElseGet() Example

1. Introduction

In this tutorial, We'll learn java 8 Optional API orElseGet() method examples and where to use.

2. Syntax

[lock]
public T orElseGet(Supplier<? extends T> other)

Return the value if present, otherwise invoke other and return the result of that invocation. This method takes the Supplier Functional Interface. [/lock]

if the Supplier is null, it throws NullPointerException.