Title: Java 8 flatMap Example - Java Code Geeks
Open Graph Title: Java 8 flatMap Example - Java Code Geeks
Description: Hello readers, in this tutorial, we will learn about Java8 Streams API flatMap() method and in which structure it can be used.
Open Graph Description: Hello readers, in this tutorial, we will learn about Java8 Streams API flatMap() method and in which structure it can be used.
Mail addresses
support@javacodegeeks.com
Opengraph URL: https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/
Generator: WordPress 6.9.4
Domain: examples.javacodegeeks.com
{"@context":"https://schema.org","@graph":[{"@type":"Article","@id":"https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/#article","isPartOf":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/"},"author":{"name":"Yatin","@id":"https://examples.javacodegeeks.com/#/schema/person/9874407a37b028e8be3276e2b5960d13"},"headline":"Java 8 flatMap Example","datePublished":"2018-02-01T13:00:58+00:00","dateModified":"2019-02-25T08:37:56+00:00","mainEntityOfPage":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/"},"wordCount":912,"commentCount":0,"publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"image":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","keywords":["core java","Java","Java 8"],"articleSection":["Core Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/#respond"]}]},{"@type":"WebPage","@id":"https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/","url":"https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/","name":"Java 8 flatMap Example - Java Code Geeks","isPartOf":{"@id":"https://examples.javacodegeeks.com/#website"},"primaryImageOfPage":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/#primaryimage"},"image":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","datePublished":"2018-02-01T13:00:58+00:00","dateModified":"2019-02-25T08:37:56+00:00","description":"Hello readers, in this tutorial, we will learn about Java8 Streams API flatMap() method and in which structure it can be used.","breadcrumb":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/#primaryimage","url":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https://examples.javacodegeeks.com/java-development/core-java/java8-flatmap-example/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://examples.javacodegeeks.com/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https://examples.javacodegeeks.com/category/java-development/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https://examples.javacodegeeks.com/category/java-development/core-java/"},{"@type":"ListItem","position":4,"name":"Java 8 flatMap Example"}]},{"@type":"WebSite","@id":"https://examples.javacodegeeks.com/#website","url":"https://examples.javacodegeeks.com/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://examples.javacodegeeks.com/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https://examples.javacodegeeks.com/#organization","name":"Exelixis Media P.C.","url":"https://examples.javacodegeeks.com/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/logo/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https://examples.javacodegeeks.com/#/schema/logo/image/"},"sameAs":["https://www.facebook.com/javacodegeeks","https://x.com/javacodegeeks"]},{"@type":"Person","@id":"https://examples.javacodegeeks.com/#/schema/person/9874407a37b028e8be3276e2b5960d13","name":"Yatin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/person/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2023/09/cropped-Yatin-Batra_avatar_1515758148-96x96.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2023/09/cropped-Yatin-Batra_avatar_1515758148-96x96.jpg","caption":"Yatin"},"description":"An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).","sameAs":["https://www.javacodegeeks.com"],"url":"https://examples.javacodegeeks.com/author/yatin-batra/"}]}
{"@context":"http:\/\/schema.org","@type":"BreadcrumbList","@id":"#Breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"item":{"name":"Home","@id":"https:\/\/examples.javacodegeeks.com\/"}},{"@type":"ListItem","position":2,"item":{"name":"Java Development","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"}},{"@type":"ListItem","position":3,"item":{"name":"Core Java","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"}}]}
{"@context":"http:\/\/schema.org","@type":"Article","dateCreated":"2018-02-01T15:00:58+02:00","datePublished":"2018-02-01T15:00:58+02:00","dateModified":"2019-02-25T10:37:56+02:00","headline":"Java 8 flatMap Example","name":"Java 8 flatMap Example","keywords":"core java,Java,Java 8","url":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/java8-flatmap-example\/","description":"Hello readers, in this tutorial, we will learn about Java8 Streams API flatMap() method and in which structure it can be used. 1. Introduction A flatMap() method is a Java8 programming operation which","copyrightYear":"2018","articleSection":"Core Java","articleBody":"Hello readers, in this tutorial, we will learn about Java8 Streams API flatMap() method and in which structure it can be used.\n1. Introduction\nA flatMap() method is a Java8 programming operation which takes a single function as an argument. This function accepts the T parameter as an input argument and returns a stream of R parameter. When this function is applied to each element of this stream, it constructs a stream of new values. All the generated elements of these new streams are then again copied to a recent stream, which will then act as a return value of this method.\n\n \nTo add further, Stream\u2019s flatMap() method is a merger of two operations i.e. a Map operation and a Flattening operation. To understand this better, let\u2019s take an example of multiple lists having String elements such as {a, b}, {c, d, e} etc. Now, if developers want to retrieve all the elements in a single concatenation, they can\u2019t use the Stream\u2019s map() method as we have an irregular structure. To solve this problem, developers can use the flatMap() method to flatten it into a structure like {a, b, c, d, e, .. }. The below diagram explains this.\n\n\n1.1 Method Syntax\nIn java.util.stream.Stream<T>, the flatMap() method is defined as,\n<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)\n\nWhere,\n\n \tThe flatMap() method takes the instance of Function<T,R>, named mapper as an input argument. This converts the current type T elements to another stream of type R\n \tThis method returns an output stream of type R elements which is literally a flattened stream obtained when the mapper is applied on the input stream\u2019s elements of type T\n \tFor \"x\" elements in an input stream of type T, developers first get the \"x\" streams of type R and later these \"x\" streams are then flattened into a single stream of type R. Thus, a Stream<Stream<R>> becomes Stream<R>\n\n1.2 Stream.map() vs. Stream.flatMap()\n\n \tThe Stream\u2019s map() method produces or returns a single result value, which is sent to the Output stream\n \tThe Stream\u2019s flatMap() method produces or returns a Stream of elements\n \tThe flatMap() method is a combination of Map and Flattening operation\n \tThe map() method is only used for modification while the flatMap() method is used for both flattening and modification\n \tThe flatMap() method replaces a value with a Stream and join all Streams together\n\nNow, open up the Eclipse Ide and I will explain further about the usage of Stream\u2019s API flatMap() method in Java8 programming.\n2. Java8 flatMap Example\n2.1 Tools Used\nWe are using Eclipse Oxygen, JDK 1.8 and Maven.\n2.2 Project Structure\nFirstly, let\u2019s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!\n\n\n2.3 Project Creation\nThis section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.\n\n\n\nIn the New Maven Project window, it will ask you to select project location. By default, 'Use default workspace location' will be selected. Select the 'Create a simple project (skip archetype selection)' checkbox and just click on next button to proceed.\n\n\n\nIt will ask you to 'Enter the group and the artifact id for the project'. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.\n\n\n\nClick on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:\n\npom.xml\n<project xmlns=\"http:\/\/maven.apache.org\/POM\/4.0.0\" xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:schemaLocation=\"http:\/\/maven.apache.org\/POM\/4.0.0 http:\/\/maven.apache.org\/xsd\/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0<\/modelVersion>\n\t<groupId>Java8FlatmapEx<\/groupId>\n\t<artifactId>Java8FlatmapEx<\/artifactId>\n\t<version>0.0.1-SNAPSHOT<\/version>\n\t<packaging>jar<\/packaging>\n<\/project>\n\nDevelopers can start adding the dependencies that they want. Let\u2019s start building the application!\n3. Application Building\nBelow are the steps involved in explaining this tutorial.\n3.1 Java Class Implementation\nLet\u2019s create the required Java files. Right-click on the src\/main\/java folder, New -> Package.\n\n\n\nA new pop window will open where we will enter the package name as: com.jcg.java.\n\n\n\nOnce the package is created in the application, we will need to create the implementation class to demonstrate the flatMap() method used. Right-click on the newly created package: New -> Class.\n\n\n\nA new pop window will open and enter the file name as: FlatmapDemo. The implementation class will be created inside the package: com.jcg.java.\n\n\n3.1.1 Example of flatMap Method\nHere is the complete Java program to demonstrate the use of Stream.flatMap() method in Java8 programming. In this example, we have a Stream of the list of String elements and by using the flatMap() method we convert this into a Stream of String elements.\n\nFlatmapDemo.java\npackage com.jcg.java;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\n\/** \n * This java program demonstrates the use of 'flatMap()' method in Java8 programming. \n * The 'flatMap()' function is used to convert a Stream of list of values to a Stream of values and this process is called \"Flattening of Streams\". \n *\n * @author Batra, Yatin\n **\/\npublic class FlatmapDemo {\n\n\tpublic static void main(String[] args) {\n\n\t\tList<String> houseGryffindor = Arrays.asList(\"Albus\", \"Harry\", \"Ron\", \"Hermione\");\n\t\tList<String> houseHufflepuff = Arrays.asList(\"Bridget\", \"Cedric\", \"Nymphadora\");\n\t\tList<String> houseRavenclaw = Arrays.asList(\"Luna\", \"Garrick\", \"Filius\");\n\t\tList<String> houseSlytherin = Arrays.asList(\"Severus\", \"Tom\", \"Phineas\");\n\n\t\tList<List<String>> hogwarts = new ArrayList<List<String>>(); \n\t\thogwarts.add(houseGryffindor);\n\t\thogwarts.add(houseHufflepuff);\n\t\thogwarts.add(houseRavenclaw);\n\t\thogwarts.add(houseSlytherin);\n\n\t\t\/\/ Printing All Hogwarts Houses In Pre-Java8 World\n\t\tList<String> listOfAllHouses = new ArrayList<String>();\n\t\tfor(List<String> house : hogwarts) {\n\t\t\tfor(String hName : house) {\n\t\t\t\tlistOfAllHouses.add(hName);\n\t\t\t}\n\t\t}\n\n\t\tSystem.out.println(\"<!---------------Hogwarts Houses---------------!>\");\n\t\tSystem.out.println(listOfAllHouses);\n\n\t\tSystem.out.println();\n\n\t\t\/\/ Now let's Achieve This By Using 'flatMap()' Method In Java8 \n\t\tList<String> flatMapList = hogwarts.stream().flatMap(hList -> hList.stream()).collect(Collectors.toList()); \n\t\tSystem.out.println(\"<!---------------Hogwarts Houses Using Java8---------------!>\"); \n\t\tSystem.out.println(flatMapList);\t\t\n\t}\n}\n\n4. Run the Application\nTo run the application, developers need to right-click on the class, Run As -> Java Application. Developers can debug the example and see what happens after every step!\n\n\n5. Project Demo\nThe above code shows the following logs as output.\n# Logs for 'FlatmapDemo' #\n=====================\n<!---------------Hogwarts Houses---------------!>\n[Albus, Harry, Ron, Hermione, Bridget, Cedric, Nymphadora, Luna, Garrick, Filius, Severus, Tom, Phineas]\n\n<!---------------Hogwarts Houses Using Java8---------------!>\n[Albus, Harry, Ron, Hermione, Bridget, Cedric, Nymphadora, Luna, Garrick, Filius, Severus, Tom, Phineas]\n\nThat\u2019s all for this post. Happy Learning!\n6. Conclusion\nIn this tutorial, we had an in-depth look at the Stream.flatMap() method with an example. I hope this article served you whatever you were looking for.\n7. Download the Eclipse Project\nThis was an example of the flatMap() method in Java8.\nDownload\nYou can download the full source code of this example here: Java8FlatmapEx","publisher":{"@id":"#Publisher","@type":"Organization","name":"Examples Java Code Geeks","logo":{"@type":"ImageObject","url":"\/wp-content\/uploads\/2013\/05\/JavaCodeGeeks-logo.png"},"sameAs":["https:\/\/feeds.feedburner.com\/examplesjavacodegeeks","https:\/\/www.facebook.com\/javacodegeeks","https:\/\/twitter.com\/javacodegeeks","https:\/\/www.linkedin.com\/groups\/3810709\/","https:\/\/www.youtube.com\/channel\/UCxoUc7Rar2q90Gu0nT2ffuQ","https:\/\/github.com\/javacodegeeks\/"]},"sourceOrganization":{"@id":"#Publisher"},"copyrightHolder":{"@id":"#Publisher"},"mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/java8-flatmap-example\/","breadcrumb":{"@id":"#Breadcrumb"}},"author":{"@type":"Person","name":"Yatin","url":"https:\/\/examples.javacodegeeks.com\/author\/yatin-batra\/"},"image":{"@type":"ImageObject","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":1200,"height":150}}
| og:locale | en_US |
| og:type | article |
| og:site_name | Examples Java Code Geeks |
| article:publisher | https://www.facebook.com/javacodegeeks |
| article:published_time | 2018-02-01T13:00:58+00:00 |
| article:modified_time | 2019-02-25T08:37:56+00:00 |
| og:image | https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg |
| og:image:width | 150 |
| og:image:height | 150 |
| og:image:type | image/jpeg |
| author | Yatin |
| twitter:card | summary_large_image |
| twitter:creator | @javacodegeeks |
| twitter:label1 | Written by |
| twitter:data1 | Yatin |
| twitter:label2 | Est. reading time |
| twitter:data2 | 7 minutes |
| None | IE=edge |
| msapplication-TileImage | https://examples.javacodegeeks.com/wp-content/uploads/2013/05/JavaCodeGeeks-favIcon.png |
Links:
Viewport: width=device-width, initial-scale=1.0
Robots: index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1