Sunday, September 8, 2024
HomeJavaJava Stream + map + flatMap + Collectors.toSet() Instance Tutorial

Java Stream + map + flatMap + Collectors.toSet() Instance Tutorial


Howdy guys, I used to be looking for instance of flatMap on-line however did not
discovered one, so created my very own. As identify counsel flatMap is used to
flatten stream like unwinding a number of listing of values. For instance you’ve got a
Stream of Record of Integer and also you wish to create Stream of Integer by
unwinding these listing, you are able to do that utilizing
FlatMap operate

from java.util.Stream class. Coming
again to flatMap, its truly a basic idea which is offered in different
useful programming language like
Scala. Identical to map() operate works
by making use of a operate to every aspect within the Stream, flatMap works by
making use of a operate that returns a sequence for every aspect within the listing, and
flattening the outcomes into Stream or one other listing. 
It may be perceive simply if you understand how Map works in useful
programming, so let first see that,  through the use of
map operate in Java
we will remodel listing of
(2,3,5,7,11) into listing
(4,9,15,49,121) the place every aspect
is squared.so simple as that flat can
convert listing of listing of String into a listing of Integer
by reworking or changing String to quantity and flattening a Record of Record
into an even bigger and single Record.
Truly this flattening occurs at Stream degree and you may
gather all the weather right into a Record or Set or some other object utilizing
Collectors. On this instance, we now have used
Collectors.toList() to gather all
the weather right into a Record. 

It mentioned {that a} image is price a thousand price, here’s a image
which explains flatMap, now you inform me in feedback whether or not this image is
price a thousand phrase? did you perceive
how flatmap methodology works
by this diagram? I’d love to listen to your ideas


If you’re nonetheless not clear then let me clarify this diagram to you in
few phrases. On this diagram, we cross a operate to
flatMap() methodology

which convert a circle to diamond. Then we apply this flatMap to a Stream of
circle. flatMap then convert that stream of circle object to stream of diamond
utilizing the operate we equipped. 

When and The right way to use flatMap in Java 8 Stream? Instance 

When you’ve got listing of listing and also you wish to flat that right into a single listing then
you should use flatMap methodology, similar goes for set of set or Assortment of
Assortment.

FlatMap + Collector Example in Java 8 - List of Object and Stream Example

Right here is the entire code instance:

bundle check;

import java.util.ArrayList;
import java.util.Record;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Java Program to reveal find out how to use flatMap in Java 8.
 * As identify suggests flatMap is used to flatten a group of assortment e.g.
 * listing of listing of numbers.
 *
 * @creator Javin
 */
public class FlatMapDemoInJava8 {

    public static void predominant(String args[]) {

        // p1 has three notes of 1,5 and 10
        Particular person p1 = new Particular person("P1");
        p1.add(1);
        p1.add(5);
        p1.add(10);
       
        // p2 has 5 notes of 10,20,50 and 5
        Particular person p2 = new Particular person("P2");
        p2.add(10);
        p2.add(20);
        p2.add(50);
        p2.add(5);
       
        // Now, let's learn the way many various observe staff has
        Record staff = new ArrayList<>();
        staff.add(p1);
        staff.add(p2);
       
        Set setOfDistinctNote = staff.stream()
                                               .map( p -> p.getNotes())
                                               .flatMap(l -> l.stream())
                                               .gather(Collectors.toSet());
       
        System.out.println("Variety of distinct notes in staff : " + setOfDistinctNote);
    }

}

class Particular person{
    non-public String identify;
    non-public Record notes = new ArrayList<>();
   
    public Particular person(String identify){
        this.identify = identify;
    }
   
    public void add(Integer observe){
        notes.add(observe);
    }

    public Record getNotes(){
        return notes;
    }
   
    @Override
    public String toString() {
        return String.format(identify + notes);
    }  
   
}

Output
Variety of distinct notes in staff : [1, 50, 20, 5, 10]

Distinction between map() and flatMap() strategies in Java

The next examples present the variations between map and flatMap on a
sequence of String, though examples are given in
Scala programming language
but it surely relevant to Java as nicely. 

scala> val fruits = Seq("apple", "banana", "orange")
fruits: Seq[java.lang.String] = Record(apple, banana, orange)

scala> fruits.map(_.toUpperCase)
res0: Seq[java.lang.String] = Record(APPLE, BANANA, ORANGE)

scala> fruits.flatMap(_.toUpperCase)
res1: Seq[Char] = Record(A, P, P, L, E, B, A, N, A, N, A, O, R, A, N, G, E)

Fairly a distinction, no? As a result of flatMap treats a String as a sequence of Char,
it flattens the ensuing listing of strings right into a sequence of Char. flatMap is
a mix of map and flatten, so it first runs map on the sequence, then
runs flatten, giving the consequence proven.

You can even see  the
distinction between map and flatMap in Java
for a easy String to integer conversion instance. Here’s a good diagram
which additionally explains the distinction between map and flatmap in Java
clearly. 

That is all about
find out how to use flatMap operate with collector in Java. You need to use flatmap
to each flatten and remodel an object. For instance, in case you have a listing of
listing of String then you’ll be able to convert that into a listing of Integer utilizing flatMap
operate in Java. Map is used to use a operate to every aspect of listing to
remodel that, whereas flatMap is used to flatten a Stream of Stream right into a
Stream of one thing like quantity, String or no matter. 

Different Java Practical Programming tutorials chances are you’ll like

I counsel you attempt to observe flatMap operate with easy workouts like
changing Record of Record of String to Record of Integer and so forth to grasp this
idea and Record of Record of Workers to Record of their Division and so forth. 



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments