[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 super T, ? extends R> 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 withfilter()
andreduce()
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!
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
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.
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!
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?
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
Wow! In the end I got a web site from where I be capable of truly obtain useful information regarding my study and knowledge.
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!
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.
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.
It is not my first time to pay a quick visit this site, i am browsing this site
dailly and take fastidious facts from here every day.
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
When some one searches for his necessary thing, so he/she wants to
be available that in detail, thus that thing is maintained over here.
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.
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.
It’s remarkable to pay a quick visit this web page and reading the views of all
friends regarding this article, while I am also keen of getting knowledge.
This excellent website truly has all of the information I
needed about this subject and didn’t know who to ask.
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!
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.
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
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.
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!
Your means of explaining the whole thing in this article is truly good, all can easily understand it, Thanks a lot.
This іnfo is priceless. Where can I find oᥙt more?
Great post.
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 =)
I visited various web sites but the audio quality for audio songs existing at this web site
is actually excellent.
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
Hi there, this weekend is pleasant designed for me, because this moment i am reading this fantastic educational article here at my residence.
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…
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.
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!
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
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
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!
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!
I am sure this paragraph has touched all the internet users, its
really really nice article on building up new weblog.
I visited many web pages however the audio quality for audio songs existing at this site is really marvelous.
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!
what color is hemp fabric
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!!
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!
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
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.
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.
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.
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.
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.
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.
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!
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.
I like what you guys are up too. This sort of clever work and reporting!
Keep up the terrific works guys I’ve incorporated you guys
to my own blogroll.
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!
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.
I every time emailed this web site post page to all my friends,
because if like to read it next my friends will too.
I really like it when individuals come together and share thoughts.
Great blog, keep it up!
Wow, fantastic blog structure! How lengthy have you ever been running a blog for?
you make running a blog glance easy. The overall look of your web site is magnificent, let alone
the content!
What’s up, every time i used to check website posts here in the early hours in the break of day,
because i love to learn more and more.
I always used to study piece of writing in news papers but now as I am a
user of net so from now I am using net for content, thanks to web.
WOW just what I was looking for. Came here by searching for Erna Kime
Touche. Sound arguments. Keep up the good work.
Great wordpress blog here.. It’s hard to find quality writing like yours these days. I really appreciate people like you! take care
buraya tiklayin ve seslendirme hizmeti satin alin
Great line up. We will be linking to this great article on our site. Keep up the good writing.
Best view i have ever seen !
Great post. I am facing a couple of these problems.
buraya tikla ve imleme satin al
Has anyone ever shopped at Angel Vapors? 🙂
Is anyone here in a position to recommend Bodies and Playsuits? Cheers x
An excellent article. I have now learned about this. Thanks admin
Can anyone able to recommend comprehensive Central Heating Repairs Business Data? Thank you 🙂
Hi everyone , can anyone suggest where I can buy Blue Liquid 4oz Hemp Oil 1000mg By Rsho?
You’re so cool! I do not think I have read through something like
this before. So nice to find another person with some genuine
thoughts on this subject. Seriously.. thank you
for starting this up. This site is something that is required on the web,
someone with a little originality!
An excellent article. I have now learned about this. Thanks admin
An excellent article. I have now learned about this. Thanks admin
An excellent article. I have now learned about this. Thanks admin
Hello, just wanted to mention, I liked this post.
It was inspiring. Keep on posting!
Well I definitely enjoyed studying it. This tip offered by you is very effective for proper planning.
An excellent article. I have now learned about this. Thanks admin
whoah this blog is great i love reading your articles. Keep up the good work! You know, lots of people are searching around for this information, you can aid them greatly.
An excellent article. I have now learned about this. Thanks admin
From my notice, shopping for technology online may be easily expensive, however there are some how-to’s that you can use to obtain the best products. There are continually ways to uncover discount bargains that could help to make one to have the best gadgets products at the smallest prices. Great blog post.
Fantastic blog! Do you have any recommendations for aspiring writers? I’m planning to start my own website soon but I’m a little lost on everything. Would you suggest starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely overwhelmed .. Any recommendations? Kudos!
I just could not depart your website prior to suggesting that I extremely enjoyed the standard information a person provide for your visitors? Is going to be back often to check up on new posts
An excellent article. I have now learned about this. Thanks admin
Very good post. Much obliged.
can i get vape delivery reddit
I was very happy to uncover this web site. I wanted to thank you for your time due to this wonderful read!!
I have witnessed that wise real estate agents almost everywhere are getting set to FSBO Marketing. They are knowing that it’s more than merely placing a sign in the front area. It’s really pertaining to building interactions with these vendors who one of these days will become consumers. So, after you give your time and energy to supporting these suppliers go it alone : the “Law associated with Reciprocity” kicks in. Good blog post.
An excellent article. I have now learned about this. Thanks admin
An excellent article. I have now learned about this. Thanks admin
An excellent article. I have now learned about this. Thanks admin
An excellent article. I have now learned about this. Thanks admin
An excellent article. I have now learned about this. Thanks admin
An excellent article. I have now learned about this. Thanks admin
Has anyone vaped DRINX Premium Ejuice E-Juice?
Has anyone ever been to Pure Vapor, LLC Vape Store in 2650 SW Wilshire Blvd Suite 400?
If you wish for to get a great deal from this piece of writing then you have to apply these methods to your won blog.
can i take my vape on a airplane
I was wondering if anyone knows what happened to Dimepiece Los Angeles celebrity streetwear brand? I am unable to proceed to the checkout on Dimepiecela site. I have read in Women’s Health Mag that they were bought out by a UK hedge fund in excess of $50 million. I’ve just bought the Meditate Stainless Steel Water Bottle from Amazon and absolutely love it xox
Consequently how will you obtain the suitable jacksonville divorce attorney information? Where by is it possible to come across totally free points, programs, as well as approaches for creating wealth on the net? You might possibly shell out a large amount upon products out there online…or you may join our Money Ideas Number and today i want to promote this specific awesome tips to you absolutely cost-free.
I like the layout of your blog and Im going to do the same for mine. Do you have any tips? Please PM ME.
health plans may be expensive but it is really very necessary to get one for yourself`
I truly appreciate this post. I¡¦ve been looking everywhere for this! Thank goodness I found it on Bing. You’ve made my day! Thanks again Pristina Travel
I’d have got to check with you here. Which is not some thing I usually do! I quite like reading a post that may get people to believe. Also, thanks for permitting me to comment!
Does anyone know what happened to Dime Piece LA celebrity streetwear brand? I am unable to proceed to the checkout on Dimepiecela site. I’ve read in Vogue that they were acquired by a UK-based hedge fund for $50 m. I’ve just bought the Dimepiece Case Mate Tough Phone Cases from Ebay and absolutely love it xox
Pretty nice post. I recently stumbled upon your blog and wished to state that I’ve actually appreciated searching your blog content. After all I will be registering to your own nourish and i also we imagine you compose once more quickly!
Trabzon gündemine dair haberleri okuyabilirsiniz.
ip kamera canlı yayın ve tv hosting hizmeti
Galatasarayın en iyi forum sitesi mutlaka ziyaret edin.
Trabzonun haber sitesi.
ip kamera canlı yayın ve tv hosting hizmeti
Samsun gündem haberlerini anlık takip edebilirsiniz.
Samsun iline ait güncel ve son dakika haberlerini okuyabilirsiniz.
Güncel trabzon haberlerini okuyun.
Trabzon haberlerini okuyabilirsiniz.
Has anyone visited Vape Nation? 😉
Has anybody ever shopped at The Vape Club Ecig Shop located in 1429 15th Ave?
Im thankful for the blog post. Will read on…
Has anybody ever shopped at Leisure Liquids Ltd Ecig Shop in 206 N Minnesota St?
koe no katachi a silent voice gano el premio de la academia de japon
noticias este ano mas de 270 abogados abandonaron los 10 bufetes de abogados mas rentables de nueva york adonde se fueron
excel ms excel como usar la funcion filedatetime vba
las diferencias entre factoring y descuento de facturas
Has anyone ever been to Vape Lounge Ecig Shop located in 17230 S Tamiami Trail Suite 8?
cemdri centro de rehabilitacion integral y audiometria
Best View i have ever seen !
cemdri centro de rehabilitacion integral y audiometria
Your email address will not be published. Required fields are marked *
Your email address will not be published. Required fields are marked scsc
s
Leave a Reply
locecwefe
my lov htis
i lov eyi
lov eto sef
very sad to hear h
m lvrrv
can i use nitecore micro usb 18650 in vape