Saturday, April 20, 2024
HomeJava3 Examples of flatMap() of Stream in Java

3 Examples of flatMap() of Stream in Java


Good day guys, in case you are doing Java growth then you could have come throughout the flatMap() technique on Stream and Optionally available Class. The flatMap() technique is extension of map() operate because it does each flattening and mapping (or transformation) as a substitute of simply transformation executed by map() technique. I’ve defined the distinction between map() and flatMap() earlier intimately, however simply to revise, let’s revisit it. In case you have an inventory of String e.g. {“credit score”, “debit”, “grasp”, “visa”} then you need to use the map() technique to get an inventory of integer the place every worth is size of corresponding String e.g. listing.stream().map(s -> s.size()) will produce {6, 5, 6, 4}. That is referred to as transformation as a result of you’ve gotten remodeled an stream of String to a Stream of integer

The flatMap() operate comes into the image, when we’ve two degree of nesting e.g. a listing of listing or a stream of streams. It than flatten the stream of stream to supply stream of values. 

For instance, suppose you’ve gotten listing of orders and every order comprises listing of lineItems, now if you’d like an inventory of LineItems for all orders then you need to use flatMap() operate of Stream class. Yet one more instance of flatMap is, suppose, you’ve gotten an inventory of states and every state has listing of voters, now how do you get all of the voters for the nation? Properly, simply use the flatMap() technique. 

If these examples nonetheless does not make a lot sense to you and you aren’t in a position to perceive what’s flatMap, the way it works and when to make use of flattMap()  in Java then right here is my final try with a concrete code  examples:

Suppose, I’ve an inventory of Books and every e-book has listing of Chapters as proven under:

class Ebook{
Checklist<Chapters> listOfChapters

...

}

I’ve 

Checklist<Ebook> javaBooks = Arrays.asList(new Ebook[]{book1, book2})

now, I can retrieve listing of chapters from this listing of books by utilizing the flatMap() technique in Java as proven under:

Checklist<String> listOfChapters = listOfBooks.stream()
                           .flatMap(e-book -> e-book.getChapters().stream())
                           .accumulate(Collectors.toList())

You may see the output first to know what flatpMap() did for you:

listing of books : [Effective Java, Clean Code]
listing of chapters: [item 1, item 2, chapter 1, chapter 2]

Although, you shouldn’t neglect to name the stream() technique on the listing retrieved by getChapters() as flatMap operates on Stream not Checklist. If you wish to be taught Stream API in Java in depth then you may as well see these Java Collections and Stream programs and books to be taught extra about Stream.flatMap()in Java. 

3 Examples of flatMap() function of Stream in Java

3 Examples of FlatMap operate in Java Stream

Right here is our pattern Java program to show the utilization of flatMap() technique in Java 8. I’ve proven three foremost examples of flatMap, the primary one is used to flatten an inventory of listing which comprises String, the second is used to flatter an inventory of listing which contemplate integer and third one is used to flatten an inventory of customized objects, e-book in our case. 

The third instance is essentially the most sensible and you’ll more likely to face such sort of eventualities in actual world programming.  

However, First let’s examine our Ebook class on which we are going to function flatMap() operate.

Ebook Class:

class Ebook{
personal Checklist<String> chapters;
personal String identify;

public Ebook (String identify, Checklist<String> chapters){
this.identify = identify;
this.chapters = chapters;
}

public Checklist<String> getChapters(){
return chapters;
}

@Override
public String toString() {
return identify;
} 


}

And, now see the precise check class which can present you 3 methods to make use of flatMap() operate in Java 8, In first instance we’ve used flatMap with listing of String whereas in second instance we’ve used flatMap with listing of integers and in final examples we’ve used flatMap operate and Stream with an inventory of customized objects in order that you understand how one can rework and flatten listing of each commonplace Java objects in addition to any customized objects you’ve gotten in your utility like Person, Worker, Order, Commerce, or Ebook and so on.

package deal check;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Checklist;
import java.util.stream.Collectors;


public class Check {

public static void foremost(String[] args) {


Checklist<Checklist<String>> listOfListOfString = new ArrayList<>();
listOfListOfString.add(Arrays.asList("grasp", "visa"));
listOfListOfString.add(Arrays.asList("flying", "reward"));
listOfListOfString.add(Arrays.asList("apple pay", "samsung pay"));

Checklist<String> listOfJustStrings = listOfListOfString.stream()
.flatMap(listing -> listing.stream())
.accumulate(Collectors.toList());
System.out.println("listing of playing cards: " + listOfJustStrings);



Checklist<Checklist<Integer>> listOfListOfInts = new ArrayList<>();
listOfListOfInts.add(Arrays.asList(2, 4));
listOfListOfInts.add(Arrays.asList(3, 9));
listOfListOfInts.add(Arrays.asList(4, 16));

Checklist<Integer> listOfIntegers = listOfListOfInts.stream()
.flatMap(listing -> listing.stream())
.accumulate(Collectors.toList());
System.out.println("listing of integers : " + listOfIntegers);



Ebook effectiveJava = new Ebook("Efficient Java", Arrays.asList("merchandise 1", "merchandise 2"));
Ebook cleanCode = new Ebook("Clear Code", Arrays.asList("chapter 1", "chapter 2"));

Checklist<Ebook> listOfBooks = new ArrayList<>();
listOfBooks.add(effectiveJava);
listOfBooks.add(cleanCode);

Checklist<String> listOfChapters = listOfBooks.stream()
.flatMap(e-book -> e-book.getChapters().stream())
.accumulate(Collectors.toList());

System.out.println("listing of books : " + listOfBooks);
System.out.println("listing of chapters: " + listOfChapters);
}

}


Output

listing of playing cards: [master, visa, flying, reward, apple pay, samsung pay]

listing of integers : [2, 4, 3, 9, 4, 16]

listing of books : [Effective Java, Clean Code]

listing of chapters: [item 1, item 2, chapter 1, chapter 2]

You may see that the ultimate result’s flattened, there is no such thing as a listing of listing, however simply listing of values. The Stream class additionally gives three overloaded model of flatMap() technique e.g. the flatMapToInt(), flatMaptoLong() and flatMapToDouble(), to work with lengthy, int, and double primitives’ values.  

These are specialised model of flatMap operator which returns IntStream, LongStream and DoubleStream respectively. When you want one in all them then you need to use these strategies for flattening. Typically you utilize specialised Stream like IntStream whenever you need to keep away from the price of boxing and unboxing between int and Integer and that is why IntStream carry out higher when you’re working with int primitive values. 

That is all about the right way to use flatMap() in Java 8. The flatMap() technique is outlined in Stream class of java.util.stream package deal and its one of the helpful useful operation you’ve gotten in JDK. It’s extremely helpful with Collections and may help to resolve lot of queries as proven within the instance in first paragraph. Simply keep in mind the distinction between map() and flatMap() in Java, former do exactly transformation, whereas later does each transformation and flattening.

         

Associated Java 8 Lambda and Stream Tutorials chances are you’ll like

  • The best way to use peek() technique in Java 8 (instance)
  • 50 Java 8 Lambda, Stream, and useful interview questions (lambda questions)
  • The best way to filter Assortment utilizing Streams in Java 8 (examine right here)
  • 15 Spring Information JPA Interview Questions (listing)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • Prime 5 Books to Be taught Java 8 (learn right here)
  • The best way to use filter() technique in Java 8 (tutorial)
  • 15 Java Microservice Interview questions (microservice questions)
  • The best way to implement Comparator utilizing lambda expression (see right here)
  • 50+ SQL and Database Telephone Interview questions (SQL questions)
  • 20+ JUnit Interview Questions for Java builders (questions)
  • 17 Spring AOP Interview Questions with Solutions (listing)
  • 25 Spring Safety Interview Questions with Solutions (questions)
  • The best way to use forEach() technique in Java 8 (instance)
  • The best way to use Stream API in Java 8 (be taught right here)
  • Understanding Default strategies of Java 8 (be taught right here)
  • The best way to be part of String in Java 8 (instance)
  • The best way to convert Checklist to Map in Java 8 (answer)
  • 130+ Java Interview Questions with Solutions (listing)
  • The best way to use Stream class in Java 8 (tutorial)
  • 8 Finest Lambda and Purposeful Programming programs (greatest programs)

Thanks for studying this text thus far. When you like these instance of flatMap operate of Stream in Java then please share them with your mates and colleagues. In case you have any
questions or suggestions about this Java 8 tutorial then please drop a notice.

P.S.: In case you are new to Java 8 and need to be taught extra about Lambda, Stream, and different
new options in Java 8 in depth then you may as well see these greatest Java 8 to Java 16 programs. It explains all necessary options of Java 8 like lambda expressions,
streams, useful interface, Optionally available, new date, and time API, and different
miscellaneous modifications.    
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments