java - Convert an loop (while and for) to stream -
i have started working java 8 , trying convert loops , old syntax in code lambdas , streams.
so example, i'm trying convert while , loop stream, i'm not getting right:
list<string> list = new arraylist<>(); if (!oldlist.isempty()) {// old list<string> iterator<string> itr = oldlist.iterator(); while (itr.hasnext()) { string line = (string) itr.next(); (map.entry<string, string> entry : map.entryset()) { if (line.startswith(entry.getkey())) { string newline = line.replace(entry.getkey(),entry.getvalue()); list.add(newline); } } } }
i wanted know if it's possible convert above example single stream there while loop inside of loop.
as stated above, using streams here doesn't add value since makes code harder read/understand. you're doing more learning exercise. being said, doing more functional-style approach doesn't have side effect of adding list within stream itself:
list = oldlist.stream().flatmap(line-> map.entryset().stream() .filter(e->line.startswith(e.getkey())) .map(filteredentry->line.replace(filteredentry.getkey(),filteredentry.getvalue())) ).collect(collectors.tolist());
wiki
Comments
Post a Comment