Wednesday, September 11, 2019

Java 8 Optional ifPresent() - Working Example

1. Overview


In this tutorial, We'll learn how to perform an action if a value is present in Optional. Java 8 Optional ifPresent() does the job for us.

Instead of directly getting the value using get() method, first, it checks the condition value != null.

java-8-optional-ifpresent


The old way is done using the isPresent() method as below. But, ifPresent is much simplified than isPresent().

Java 8: How to Get the Last Element of a Stream in Java?

$type=blogging

1. Introduction

[post_ads]

in this tutorial, We will be looking at different ways to get the last element of a Stream in Java 8.

When we work with Stream then we have to go through one by one element of Stream. But, if we want to get directly last value and ignore the remaining preceding elements.

here are the possible ways to retrieve only the last value from the stream.

2. Using reduce() method

[lock]
reduce() method is part of the Stream API and we have to pass the lambda expression with two arguments. [/lock]

Syntax:


Optional reduce​(BinaryOperator accumulator)