How to use Java 8 Stream FlatMap Examples with List, Array

java-8-stream-flat-map-api-examples

[no_toc]
In the tutorial, we will discover more aspect of Java 8 Stream API with flatMap() function by lots of examples.
What we will do:

  • Explain how Java 8 Stream FlatMap work?
  • Apply Stream FlatMap on Java List, Array

Now let’s do more details!

Related posts:
Java 8 Stream Map Examples
Java 8 Stream Filter Examples

Java 8 Stream FlatMap

Java 8 Stream provides 2 mapping APIs: map() and flatMap()

– Both map() & flatMap() is an intermediate operation.
– Stream map() function is used to transform an input stream to a new output stream by applying a mapper function on each element.
-> What is a difference point with Stream flatMap() function?


<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

The flatMap() function will do 2 things:
– Apply mapper function to transform each element of input stream.
– Then flattens the result to a new output stream. (Not with Java 8 Stream map() function)

Stream FlatMap Java List Example

Stream FlatMap Integer List Example

We do a list of examples about Stream flatMap() function combining with others: map(), filter(), reduce()

Example 1 – Flatten Map

Example:


List<List<Integer>> -> Stream -> FlatMap -> Stream -> Collectors.toList() -> List<Integer>

– Code:


package com.ozenero.stream;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamFlatMapExamples {
	
	public static void main(String[] args) {
		List> listOfList = Arrays.asList(
					Arrays.asList(1, 2, 3, 4),
					Arrays.asList(5, 6, 7, 8),
					Arrays.asList(9, 10, 11, 12)
				);  
		
		System.out.println(listOfList);
		// [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
		
		List results = listOfList.stream()
					.flatMap(intList -> intList.stream())
					.collect(Collectors.toList());
		
		System.out.println(results);
		// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
	}
}

Example 2 – Combine flatMap() with map()

Example 2:

List<List<Integer>> -> Stream -> FlatMap (using Map) -> Stream -> Collectors.toList() -> List<Integer>

Code:

List<List<Integer>> arraylist = Arrays.asList(
			Arrays.asList(1, 2, 3, 4),
			Arrays.asList(5, 6, 7, 8),
			Arrays.asList(9, 10, 11, 12)
		);  

System.out.println(arraylist);
// [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

List<Integer> results = arraylist.stream()
			.flatMap(intList -> intList.stream().map(i -> i*2))
			.collect(Collectors.toList());

System.out.println(results);
// [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]

Example 3 – Combine flatMap() with reduce()

Example:

List<List<Integer>> -> Stream -> FlatMap -> Stream -> Reduce -> Int

Code:

List<List<Integer>> listOfList = Arrays.asList(
			Arrays.asList(1, 2, 3, 4),
			Arrays.asList(5, 6, 7, 8),
			Arrays.asList(9, 10, 11, 12)
		);  

System.out.println(listOfList);
// [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

int sum = listOfList.stream()
			.flatMap(intList -> intList.stream())
			.reduce(0, (i1, i2) -> i1 + i2);

System.out.println(sum);
// 78

Example 4 – Combine flatMap() with filter()

Example:

List<List<Integer>> -> Stream -> FlatMap ->  Filter -> Stream -> List<Integer>

Code:

List<List<Integer>> listOfList = Arrays.asList(
			Arrays.asList(1, 2, 3, 4),
			Arrays.asList(5, 6, 7, 8),
			Arrays.asList(9, 10, 11, 12)
		);  

System.out.println(listOfList);
// [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

List<Integer> results = listOfList.stream()
			.flatMap(intList -> intList.stream())
			.filter( i-> i%2==0).collect(Collectors.toList());

System.out.println(results);
// [2, 4, 6, 8, 10, 12]

Stream FlatMap String List Example

Example:

List<List<String>> -> Stream -> flatMap() -> filter() -> Stream -> Collectors.toList() -> List<String>

Code:

List<List<String>> listOfList = Arrays.asList(
			Arrays.asList("Java", "Django", "Vue", "Spring Cloud"),
			Arrays.asList("Python", "Spring Boot", "React"),
			Arrays.asList("Angular", "JQuery", "Spring JPA")
		);  

System.out.println(listOfList);
// [[Java, Django, Vue, Spring Cloud], [Python, Spring Boot, React], [Angular, JQuery, Spring JPA]]

List<String> results = listOfList.stream()
			.flatMap(strList -> strList.stream())
			.filter(str -> str.contains("Spring")).collect(Collectors.toList());

System.out.println(results);
// [Spring Cloud, Spring Boot, Spring JPA]

Stream FlatMap Custom Object List Example

– Create Developer class object:


class Developer {

	private String name;
	private Set skills;
	
	public Developer(String name, Set skills){
		this.name = name;
		this.skills = skills;
	}
	
	public String getName() {
		return this.name;
	}
	
	public Set getSkills(){
		return this.skills;
	}
	
	public String toString() {
		return "{name = " + this.name + ", skills = " + this.skills + "}";
	}
}

– Using Stream flatMap() combine with distinct() method to get all difference skill set of a List Developers.

Example:

List<Developer> -> Stream<Developer> -> FlatMap -> Stream<String> -> Distinct -> Stream<String> -> Collectors.toSet() -> Set<String>

Code:

List<Developer> developers = Arrays.asList(
			new Developer("Jack", Stream.of("Java", "Node.js", "Angular")
					  .collect(Collectors.toSet())),
			new Developer("Joe", Stream.of("C++", "ActiveMQ", "HTML", "CSS", "Java")
					  .collect(Collectors.toSet())),
			new Developer("Peter", Stream.of("Python", "Node.js", "C++", "Vue.js")
					  .collect(Collectors.toSet())),
			new Developer("Mary", Stream.of("Node.js", "Angular", "React", "CSS")
					  .collect(Collectors.toSet()))
		);  

System.out.println(developers);
// [{name = Jack, skills = [Java, Node.js, Angular]}, {name = Joe, skills = [Java, C++, CSS, HTML, ActiveMQ]}, {name = Peter, skills = [Vue.js, C++, Node.js, Python]}, {name = Mary, skills = [CSS, Node.js, React, Angular]}]

Set<String> skills = developers.stream()
			.flatMap(developer -> developer.getSkills().stream())
			.distinct()
			.collect(Collectors.toSet());

System.out.println(skills);
// [Java, Vue.js, C++, CSS, Node.js, HTML, ActiveMQ, React, Angular, Python]

Stream FlatMap Java Array Example

To apply Stream FlatMap in Array with Java 8, We do 2 steps:

  • Create Stream from Array Objects.
  • Apply Stream FlatMap for Array Objects as the same way we had done with above List Objects.

– Modify Customer class:


class Developer {

	private String name;
	private String[] skills;
	
	public Developer(String name, String[] skills){
		this.name = name;
		this.skills = skills;
	}
	
	public String getName() {
		return this.name;
	}
	
	public String[] getSkills(){
		return this.skills;
	}
	
	public String toString() {
		return "{name = " + this.name + ", skills = " + this.skills + "}";
	}
}

– Stream FlatMap Example with Java Array:


Developer[] developers = new Developer [] { 
		new Developer("Jack", new String[] {"Java", "Node.js", "Angular"}),
		new Developer("Joe", new String[] {"C++", "ActiveMQ", "HTML", "CSS", "Java"}),
		new Developer("Peter", new String[] {"Python", "Node.js", "C++", "Vue.js"}),
		new Developer("Mary", new String[] {"Node.js", "Angular", "React", "CSS"})
	};  

System.out.println(developers);
// [{name = Jack, skills = [Java, Node.js, Angular]}, {name = Joe, skills = [Java, C++, CSS, HTML, ActiveMQ]}, {name = Peter, skills = [Vue.js, C++, Node.js, Python]}, {name = Mary, skills = [CSS, Node.js, React, Angular]}]

Set skills = Arrays.stream(developers)
			.flatMap(developer -> Arrays.stream(developer.getSkills()))
			.distinct()
			.collect(Collectors.toSet());

System.out.println(skills);
// [Java, Vue.js, C++, CSS, Node.js, HTML, ActiveMQ, React, Angular, Python]

Conclusion

We had learned Java 8 Stream FlatMap with examples:

  • Apply Java 8 Stream FlatMap to Integer, String and Custom Object List
  • Combine Stream flatMap() function with others: map(), reduce(), filter(), distinct()
  • Apply Stream FlatMap to Java Array

Thanks for reading! See you later!

61 thoughts on “How to use Java 8 Stream FlatMap Examples with List, Array”

  1. Hey! This is my first comment here so I just wanted to give a quick shout out and say I really enjoy reading through your posts. Can you recommend any other blogs/websites/forums that deal with the same topics? Thank you so much!

  2. I’ve been absent for a while, but now I remember why I used to love this web site. Thanks , I will try and check back more frequently. How frequently you update your site?

  3. Thanks for the interesting things you have uncovered in your post. One thing I’d like to reply to is that FSBO human relationships are built with time. By bringing out yourself to owners the first few days their FSBO is announced, ahead of masses commence calling on Monday, you make a good relationship. By giving them instruments, educational components, free reviews, and forms, you become a great ally. By using a personal curiosity about them as well as their circumstances, you produce a solid relationship that, in many cases, pays off in the event the owners decide to go with a broker they know as well as trust – preferably you.

  4. 715563 535202Oh my goodness! an incredible write-up dude. A lot of thanks Even so My business is experiencing trouble with ur rss . Do not know why Struggle to sign up to it. Can there be everybody obtaining identical rss dilemma? Anyone who knows kindly respond. Thnkx 392438

  5. Hey! I know this is kinda off topic however I’d figured I’d ask. Would you be interested in exchanging links or maybe guest writing a blog post or vice-versa? My blog goes over a lot of the same topics as yours and I believe we could greatly benefit from each other. If you’re interested feel free to send me an email. I look forward to hearing from you! Superb blog by the way!

  6. Hiya, I am really glad I’ve found this information. Today bloggers publish just about gossips and internet and this is really annoying. A good blog with interesting content, that’s what I need. Thanks for keeping this web-site, I will be visiting it. Do you do newsletters? Can’t find it.

  7. Wow that was unusual. I just wrote an very long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyhow, just wanted to say excellent blog!

  8. hello there and thank you on your info ?I have definitely picked up anything new from right here. I did alternatively expertise some technical issues the use of this web site, since I experienced to reload the site many times previous to I could get it to load correctly. I had been considering in case your web host is OK? Now not that I’m complaining, but sluggish loading circumstances occasions will sometimes impact your placement in google and can injury your quality ranking if ads and ***********|advertising|advertising|advertising and *********** with Adwords. Well I am adding this RSS to my email and could look out for a lot more of your respective exciting content. Ensure that you update this once more soon..

  9. Appreciating the time and effort you put into your site and in depth information you offer. It’s nice to come across a blog every once in a while that isn’t the same old rehashed information. Excellent read! I’ve saved your site and I’m adding your RSS feeds to my Google account.

  10. Nice read, I just passed this onto a friend who was doing a little research on that. And he actually bought me lunch since I found it for him smile So let me rephrase that: Thank you for lunch!

  11. I got this site from my friend who informed me regardingthis site and now this time I am visiting this web page and reading very informative contenthere.

  12. continuously i used to read smaller posts which also clear their motive, and
    that is also happening with this paragraph which I am
    reading at this time.

  13. Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something.
    I think that you can do with a few pics to drive the message home
    a bit, but other than that, this is magnificent blog. A fantastic read.

    I will definitely be back.

  14. You are so cool! I don’t believe I have read through a single thing like this
    before. So wonderful to discover somebody with some genuine thoughts on this subject matter.

    Really.. many thanks for starting this up. This website is something that is needed on the web, someone with a bit of originality!

  15. Fine way of describing, and good piece of writing to obtain factsregarding my presentation focus, which i amgoing to convey in institution of higher education.

  16. It is truly a great and useful piece of information. I’m satisfied that you sharedthis useful information with us. Please keep us up to datelike this. Thanks for sharing.

  17. You really make it appear really easy together
    with your presentation but I in finding this topic to be really one
    thing which I think I might by no means understand.
    It seems too complicated and extremely large for me.
    I’m taking a look forward in your next publish, I’ll attempt to get the grasp of it!

  18. Howdy, I do believe your web site may be having web browser compatibility problems.When I take a look at your blog in Safari, it looks fine however, when opening in I.E., it has some overlapping issues.I just wanted to give you a quick heads up! Aside from that, excellent website!

  19. I’ve been browsing online more than 3 hours today, yet I never found any interesting article like yours.
    It’s pretty worth enough for me. Personally, if all website
    owners and bloggers made good content as you did, the web will be much more useful
    than ever before.

  20. Heya i am for the first time here. I came across this board and I find It truly useful & it helped me out much.

    I hope to give something back and help others like you helped me.

  21. Hello would you mind sharing which blog platform you’re using?
    I’m looking to start my own blog soon but I’m
    having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your layout seems
    different then most blogs and I’m looking for something completely unique.

    P.S Sorry for being off-topic but I had to ask!

  22. Pretty component to content. I simply stumbled upon your web site
    and in accession capital to assert that I get in fact
    enjoyed account your blog posts. Anyway I will be subscribing on your augment and even I success you
    get admission to persistently fast.

  23. Asking questions are actually good thing if you are not understanding anything fully, however this paragraph provides fastidious understandingyet.

  24. Hello! This is my first visit to your blog! We are a collection of volunteers and starting a new
    initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a wonderful job!

  25. Hi there are using WordPress for your blog platform?
    I’m new to the blog world but I’m trying to get started and set up my own. Do you need any html
    coding expertise to make your own blog? Any
    help would be greatly appreciated!

  26. It is appropriate time to make some plans for the future and it is time to be happy.I’ve learn this submit and if I could I want to suggest you some fascinating issues or advice.Maybe you could write next articles referring to this article.I wish to read even more things approximately it!

  27. I’m impressed, I must say. Seldom do I encounter a blog that’s both educative and amusing, and let me tell you, you’ve hit the nail on the head.
    The issue is an issue that not enough folks are speaking
    intelligently about. I am very happy I came across this in my hunt for something regarding this.

  28. Can I simply say what a comfort to discover somebody that truly knows what they are talking about on the web.
    You definitely understand how to bring a problem to light and
    make it important. A lot more people have to look at this and understand this side of the story.
    I was surprised that you are not more popular because you surely
    possess the gift.

  29. Just wish to say your article is as astonishing. The clearness in your put
    up is simply excellent and that i could think you are knowledgeable on this subject.

    Well together with your permission let me to grab your feed to keep updated with
    drawing close post. Thanks a million and please continue the gratifying work.

  30. Greetings, There’s no doubt that your blog may be having web browser compatibility issues.Whenever I look at your website in Safari, it looks fine however, if opening in Internet Explorer, it has some overlapping issues.I simply wanted to give you a quick heads up! Other than that, fantastic site!

  31. 108070 13155This web site is often a walk-through like the information you wanted in regards to this and didnt know who to question. Glimpse here, and you will certainly discover it. 676379

  32. I have really learned new things out of your blog post. Yet another thing to I have noticed is that in most cases, FSBO sellers may reject a person. Remember, they would prefer to not use your providers. But if anyone maintain a steady, professional connection, offering guide and keeping contact for around four to five weeks, you will usually have the capacity to win interviews. From there, a house listing follows. Cheers

  33. I really like your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to design my own blog and would like to know where u got this from. many thanks

  34. I not to mention my friends were actually examining the good tips and tricks on your web site then before long I had a horrible suspicion I had not thanked you for those strategies. All of the young boys appeared to be for that reason very interested to study all of them and have in actuality been loving these things. I appreciate you for truly being simply considerate and also for pick out some impressive information millions of individuals are really eager to discover. Our sincere apologies for not expressing appreciation to you earlier.

  35. It is in point of fact a great and useful piece of information. I’m happy that you shared this helpful information with us. Please stay us informed like this. Thanks for sharing.

  36. When I originally commented I clicked the -Notify me when new surveys are added- checkbox now each time a comment is added I recieve four emails with similar comment. Can there be in whatever way you can remove me from that service? Thanks!

  37. I do consider all of the ideas you’ve offered in your post. They are very convincing and can certainly work. Nonetheless, the posts are too short for newbies. May just you please extend them a bit from next time? Thank you for the post.

  38. Attractive component to content. I simply stumbled upon your web site and in accession capital to say that I acquire in fact loved account your blog posts. Anyway I will be subscribing for your feeds and even I achievement you get right of entry to constantly fast.

  39. Pretty nice post. I just stumbled upon your blog and wished to say that I’ve really enjoyed browsing your blog posts. After all I’ll be subscribing to your feed and I hope you write again soon!

  40. Thanks for sharing superb informations. Your site is very cool. I am impressed by the details that you’ve on this blog. It reveals how nicely you understand this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found simply the information I already searched all over the place and simply could not come across. What an ideal website.

  41. Hey there! I’ve been reading your website for some time now and finally got the bravery to go ahead and give you a shout out from Porter Tx! Just wanted to mention keep up the excellent work!

Leave a Reply

Your email address will not be published. Required fields are marked *