How to use Java 8 Stream Map Examples with a List or Array

how-to-use-java-8-stream-map-examples-feature-image

[no_toc]
Converting or transforming a List and Array Objects in Java is a common task when programming. In the tutorial, We show how to do the task with lots of Java examples code by 2 approaches:

  • Using Traditional Solution with basic Looping
  • Using a powerful API – Java 8 Stream Map

Now let’s do details with examples!

Related posts:
Java 8
Java 8 Streams

Java Transform a List with Traditional Solution by Looping Examples

Before Java 8, for mapping a List Objects, we use the basic approach with looping technical solution.

Looping Example – Java Transform an Integer List

– Example: How to double value for each element in a List?


package com.ozenero.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StreamMapExamples {
	public static void main(String[] args) {
		List intLst = Arrays.asList(1, 2, 3, 4);
		
		// How to double value for each element in a List
		// n -> n*2
		
		List newLst = new ArrayList();
		
		for(int i : intLst) {
			newLst.add(i*2);
		}
		
		System.out.println(newLst);
		// [2, 4, 6, 8]
	}
}

Looping Example – Java Transform a String List

– Example: How to uppercase string value for each element in a String List?


package com.ozenero.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StreamMapExamples {
	public static void main(String[] args) {
		List strLst = Arrays.asList("one", "two", "three", "four");
		
		// How to upper-case for each element in a List
		// one -> ONE
		
		List newLst = new ArrayList();
		
		for(String str : strLst) {
			newLst.add(str.toUpperCase());
		}
		
		System.out.println(newLst);
		// [ONE, TWO, THREE, FOUR]
	}
}

Looping Example – Transform a Custom Object List

Create a Customer class:


class Customer{
	
	private String firstname;
	private String lastname;
	
	public String getFirstname() {
		return firstname;
	}
	
	public String getLastname() {
		return lastname;
	}
	
	Customer(String firstname, String lastname){
		this.firstname = firstname;
		this.lastname = lastname;
	}
}

– Example: How to get a string list of fullname of Customer List?


List custList = Arrays.asList(
							new Customer("Jack", "Smith"),
							new Customer("Joe", "Johnson"),
							new Customer("Richard", "Brown"),
							new Customer("Thomas", "Wilson")
						);

List fullnameList = new ArrayList();

for(Customer c: custList) {
	String fullname = c.getFirstname() + " " + c.getLastname(); 
	fullnameList.add(fullname);
}

System.out.println(fullnameList);
// [Jack Smith, Joe Johnson, Richard Brown, Thomas Wilson]

Java 8 Stream Map Examples to Convert or Transform a List

With Java 8, We have a powerful Stream API map() method that help us transform or convert each element of stream with more readable code:


 Stream map(Function mapper);

-> It returns a stream consisting of the results of applying the given function to the elements of this stream.

Now we can convert or transform a List with following way:


List -> Stream -> map() -> Stream -> List

Stream Map Example with Integer List

– Example: Transform a Java number list to a double value number list by using stream map.


Integer List -> Stream -> map() -> Stream -> Another Integer List

– Code:


package com.ozenero.stream;

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

public class StreamMapExamples {
	public static void main(String[] args) {
		List intLst = Arrays.asList(1, 2, 3, 4);
		
		// How to double value for each element in a List
		// n -> n*2
		//  we use map function of stream:
		// 	List -> Stream -> map() -> Stream -> List
		
		List newLst = intLst.stream()
										.map(n->n*2)
											.collect(Collectors.toList());
		
		System.out.println(newLst);
		// [2, 4, 6, 8]
	}
}

In above code, we use collect() method to transform stream elements into another container such as a List.

Stream Map Example with String List

– Example: Convert a Java string list to an uppercase string list by Stream Map.


String List -> Stream -> map() -> Stream -> Uppercase String List

– Code:


List strLst = Arrays.asList("one", "two", "three", "four");

// How to upper-case for each element in a List
// We use map() method of Stream
// List -> Stream -> map() -> Stream -> List

List newLst = strLst.stream()
								.map(str->str.toUpperCase())
									.collect(Collectors.toList());

System.out.println(newLst);
// [ONE, TWO, THREE, FOUR]

Stream Map Example with Custom Object List

– Example: Transform an Java object list to another string list.


Customer List -> Stream -> map() -> Stream -> String List

– Code:


List custList = Arrays.asList(
		new Customer("Jack", "Smith"),
		new Customer("Joe", "Johnson"),
		new Customer("Richard", "Brown"),
		new Customer("Thomas", "Wilson")
	);

List fullnameList = custList.stream()
			.map(c -> c.getFirstname() + " " + c.getLastname())
				.collect(Collectors.toList());

System.out.println(fullnameList);
// [Jack Smith, Joe Johnson, Richard Brown, Thomas Wilson]

Parallel & Sequential Stream Map Examples

Stream provides a parallel API processing parallel(), so We can combine it with map() method to leverage the multiple cores on your computer for performance processing data.


List custList = Arrays.asList(
		new Customer("Jack", "Smith"),
		new Customer("Joe", "Johnson"),
		new Customer("Richard", "Brown"),
		new Customer("Thomas", "Wilson")
	);

custList.stream()
			.parallel()
			.map(c -> c.getFirstname() + " " + c.getLastname()) //concurrently mapping
				.forEach(System.out::println); //concurrently System.out:println
/*
	Richard Brown
	Thomas Wilson
	Joe Johnson
	Jack Smith
 */

– In above code, we use forEach() method to perform an action System.out::println for each stream element.

To switch from concurrently to sequential processing, We can use the sequential() API of Stream:


List custList = Arrays.asList(
		new Customer("Jack", "Smith"),
		new Customer("Joe", "Johnson"),
		new Customer("Richard", "Brown"),
		new Customer("Thomas", "Wilson")
	);

custList.stream()
			.parallel()
			.map(c -> c.getFirstname() + " " + c.getLastname())
			.sequential()
				.forEach(System.out::println);
/*
	Jack Smith
	Joe Johnson
	Richard Brown
	Thomas Wilson

 */

There are a difference order of items in the output between concurrently processing and sequential processing with forEach() method: result of the sequential processing remains the same order of original list while the parallel processing does NOT.

Java 8 Stream Map combines with Filter and Reduce

Java Stream Map with Filter

We can combines Stream Map with Filter mechanics.

Example:


Integer List -> Stream -> Filter odd number -> Map: double value of filtered (odd) number -> Stream -> Integer List

– Code:


List intLst = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

// 
// n -> n*2

List newLst = intLst.stream()
								.parallel()
								.filter(i -> i%2 == 1)
								.map(i->{
									System.out.println(i);
									return i*2;	
								})
								.collect(Collectors.toList());

System.out.println(newLst);

/*
	5
	3
	7
	1
	[2, 6, 10, 14]
 */

See more about Stream Filter at post: link

Java Stream Map with Reduce

Question: How to sum all number of the final stream after mapping?
We can do the calculation by using reduce() function of Java Stream:


Stream.reduce(Integer identity, BinaryOperator accumulator)

– Code:


List intLst = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

// How to double value for each element in a List
// n -> n*2

Integer total = intLst.stream()
								.parallel()
								.filter(i -> i%2 == 1)
								.map(i->{
									System.out.println(i);
									return i*2;	
								})
								.reduce(0, (i1, i2) -> i1 + i2);

System.out.println("Total: " + total);

/*
	5
	1
	3
	7
	Total: 32
 */

32 is a result of reduce funtion by sum all all numbers in final stream after mapping: (5*2 + 1*2 + 3*2 + 7*2).

Java 8 Stream Map Examples with Array

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

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

Example Code:


Customer[] customers = new Customer[] {
		new Customer("Jack", "Smith"),
		new Customer("Joe", "Johnson"),
		new Customer("Richard", "Brown"),
		new Customer("Thomas", "Wilson")
};

Arrays.stream(customers)
			.parallel()
			.map(c -> c.getFirstname() + " " + c.getLastname())
			.sequential()
				.forEach(System.out::println);
/*
	Jack Smith
	Joe Johnson
	Richard Brown
	Thomas Wilson

 */

Conclusion

We had done how to use Java 8 Stream Map with Examples:

  • How to transform Java Array or List with basic looping
  • Apply Java 8 Stream Map to Integer, String, Custom Object List
  • Combine map() method with filter() and reduce() functions of Java 8 Stream<>
  • Apply Stream Map to Java Array
  • Explore how to use parallel & sequential streams with map() method

Thanks for reading! See you later!

55 thoughts on “How to use Java 8 Stream Map Examples with a List or Array”

  1. Thank you a lot for sharing this with all folks you actually know what you’re speaking about!
    Bookmarked. Please also consult with my website =). We can have a hyperlink alternate
    arrangement between us

  2. I抳e been exploring for a little for any high quality articles or weblog posts in this sort of house . Exploring in Yahoo I finally stumbled upon this site. Reading this information So i am happy to convey that I’ve an incredibly excellent uncanny feeling I discovered just what I needed. I so much indubitably will make sure to do not omit this website and provides it a look regularly.

  3. Great blog you have here but I was curious about if you knew of any community forums that cover the same topics talked about in this article? I’d really like to be a part of group where I can get advice from other knowledgeable people that share the same interest. If you have any suggestions, please let me know. Cheers!

  4. Thanks , I’ve recently been looking for info about this subject for ages and yours is the best I’ve discovered so far. But, what in regards to the conclusion? Are you sure about the source?

  5. Wonderful blog! I found it while searching on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Many thanks

  6. Hi! This is my 1st 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!

  7. Thanks for your publication on this site. From my very own experience, occasionally softening way up a photograph may provide the photography with a bit of an artistic flare. Often however, that soft cloud isn’t just what exactly you had in mind and can sometimes spoil an otherwise good photograph, especially if you thinking about enlarging this.

  8. Appreciating the time and effort you put into your blog and detailed information you present.
    It’s nice to come across a blog every once in a
    while that isn’t the same outdated rehashed information. Excellent read!

    I’ve saved your site and I’m including your RSS feeds to my Google account.

  9. Hello there! Would you mind if I share your blog with my twitter group?
    There’s a lot of folks that I think would really
    enjoy your content. Please let me know. Many thanks

  10. Magnificent items from you, man. I’ve take into accout your
    stuff prior to and you are simply too great. I actually like
    what you’ve acquired right here, certainly like what
    you are stating and the way in which in which you assert
    it. You’re making it enjoyable and you continue to care for
    to stay it wise. I can not wait to read far more from you.

    This is actually a wonderful website.

  11. Fantastic goods from you, man. I have understand your stuff previous
    to and you’re just too great. I actually like
    what you have acquired here, really like what you are stating and
    the way in which you say it. You make it entertaining
    and you still care for to keep it wise. I can’t wait
    to read far more from you. This is actually
    a great site.

  12. This is the best weblog for anybody who needs to seek out out about this topic. You understand so much its nearly arduous to argue with you (not that I really would need匟aHa). You undoubtedly put a new spin on a topic thats been written about for years. Great stuff, just great!

  13. One important thing is that if you find yourself searching for a student loan you may find that you will want a co-signer. There are many conditions where this is true because you will find that you do not possess a past history of credit so the loan provider will require that you’ve got someone cosign the financing for you. Interesting post.

  14. Hi! This is kind of off topic but I need some guidance from an established blog. Is it hard to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about setting up my own but I’m not sure where to begin. Do you have any tips or suggestions? With thanks

  15. I precisely wanted to appreciate you again. I’m not certain the things I would have handled in the absence of those secrets provided by you on my situation. It was a difficult case in my opinion, nevertheless encountering your expert way you treated the issue forced me to leap for gladness. I will be happier for this support and even trust you realize what a powerful job you have been doing teaching the rest by way of your blog post. Most likely you’ve never got to know any of us.

  16. you’re really a good webmaster. The site loading speed is amazing. It seems that you’re doing any unique trick. Also, The contents are masterpiece. you have done a wonderful job on this topic!

  17. Terrific work! That is the type of info that are supposed
    to be shared around the web. Disgrace on Google
    for now not positioning this submit upper! Come on over and talk
    over with my site . Thank you =)

  18. I just couldn’t leave your web site before suggesting that I extremely loved the standard information a person provide for your guests?
    Is going to be again regularly in order to check out
    new posts

  19. I needed to thank you for this great read!! I absolutely enjoyed every little bit
    of it. I’ve got you book-marked to look at new things you post…

  20. I’m not sure exactly why but this weblog is loading very slow for me.
    Is anyone else having this issue or is it a problem on my end?
    I’ll check back later and see if the problem still exists.

  21. Today, I went to the beach front with my kids.

    I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed.

    There was a hermit crab inside and it pinched her ear.
    She never wants to go back! LoL I know this is totally off topic but
    I had to tell someone!

  22. I just could not go away your website prior to suggesting that I actually loved the usual info an individual provide
    for your visitors? Is going to be again often in order to inspect new posts

  23. I don’t know whether it’s just me or if perhaps everyone else
    encountering issues with your website. It appears as if some of
    the written text in your posts are running off the screen. Can someone
    else please provide feedback and let me know if this is happening to them too?

    This might be a problem with my web browser because I’ve had this happen previously.
    Thanks

  24. Woah! I’m really enjoying the template/theme of this blog. It’s simple, yet effective. A lot of times it’s tough to get that “perfect balance” between user friendliness and visual appearance. I must say you’ve done a excellent job with this. In addition, the blog loads very quick for me on Internet explorer. Superb Blog!

  25. Having read this I believed it was extremely enlightening.

    I appreciate you spending some time and energy to put this content together.
    I once again find myself spending a significant amount of time both reading and leaving comments.

    But so what, it was still worth it!

  26. Hey are using WordPress for your site platform? I’m new to the blog world but I’m trying to
    get started and set up my own. Do you need any coding knowledge to make your own blog?
    Any help would be really appreciated!

  27. Hi, i think that i saw you visited my website so i came to “return the favor”.I’m
    trying to find things to enhance my web site!I suppose
    its ok to use a few of your ideas!!

  28. I like the valuable info you provide in your
    articles. I will bookmark your blog and check once more right here regularly.
    I am fairly sure I will learn plenty of new stuff
    proper right here! Good luck for the next!

  29. Undeniably believe that which you said. Your favorite justification appeared to be on the internet the easiest thing to be aware of. I say to you, I certainly get annoyed while people consider worries that they plainly don’t know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side effect , people could take a signal. Will likely be back to get more. Thanks

  30. Have you ever thought about writing an e-book or guest
    authoring on other blogs? I have a blog based on the same information you discuss
    and would love to have you share some stories/information. I know my readers would
    enjoy your work. If you’re even remotely interested,
    feel free to send me an e-mail.

  31. I have read several just right stuff here. Certainly worth bookmarking for revisiting.
    I wonder how so much attempt you place to make this
    sort of excellent informative web site.

  32. I am not sure where you are getting your info, but great topic.
    I needs to spend some time learning more or understanding more.
    Thanks for fantastic information I was looking for this info for my mission.

  33. Your style is unique compared to other folks I’ve read stuff from.
    Thanks for posting when you have the opportunity, Guess I’ll
    just bookmark this blog.

  34. I have read some good stuff here. Certainly price bookmarking
    for revisiting. I wonder how much attempt
    you place to make this sort of fantastic informative web
    site.

  35. You could definitely see your expertise in the work you write.

    The arena hopes for even more passionate writers such as you who aren’t
    afraid to say how they believe. All the time
    go after your heart.

  36. Hey! Do you know if they make any plugins to assist with
    Search Engine Optimization? I’m trying to get my blog to rank for
    some targeted keywords but I’m not seeing very good results.

    If you know of any please share. Many thanks!

  37. I loved as much as you’ll receive carried out right
    here. The sketch is attractive, your authored subject matter stylish.

    nonetheless, you command get got an edginess over that you wish be
    delivering the following. unwell unquestionably come further formerly again as
    exactly the same nearly very often inside case you shield this hike.

  38. Good post however , I was wanting to know if you could write a litte more on this subject?
    I’d be very grateful if you could elaborate a little bit more.
    Kudos!

  39. I’m impressed, I must say. Seldom do I encounter a blog that’s both educative and entertaining,
    and without a doubt, you’ve hit the nail on the head.
    The problem is something too few men and women are speaking
    intelligently about. I’m very happy that I came across this during my hunt for something relating to this.

Leave a Reply

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