Pages

Showing posts with label Java 8 Difference. Show all posts
Showing posts with label Java 8 Difference. Show all posts

Sunday, November 15, 2020

What's the difference between map() and flatMap() methods in Java 8?

1. Overview


In this article, You'll learn what is the difference between the map() and flatMap() methods in Java 8.

Looks both methods do the same thing but actually not. Let us see each method by example programs. So that you can understand how map() and flatMap() works.

Before reading the article, it is good to have a better understanding of How to Lambda Express in java 8?

Remember, both of these methods are present in the Stream API and as well as in the Optional API.

What's the difference between map() and flatMap() methods in Java 8?


Saturday, August 1, 2020

Java 8 Iterable.forEach() vs foreach loop with examples

1. Overview


In this article, you'll learn what are the differences between the Iterator.forEach() and the normal foreach loop before java 8.

First, let us write a simple program using both approaches then you will understand what you can not achieve with the java 8 forEach.

Iterable is a collection api root interface that is added with the forEach() method in java 8. The following code is the internal implementation. Whatever the logic is passed as lambda to this method is placed inside Consumer accept() method. Just remember this for now. When you see the examples you will understand the problem with this code.
default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
Java 8 Iterable.forEach() vs foreach loop with examples