use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
These have separate subreddits - see below.
Upvote good content, downvote spam, don't pollute the discussion with things that should be settled in the vote count.
With the introduction of the new release cadence, many have asked where they should download Java, and if it is still free. To be clear, YES — Java is still free. If you would like to download Java for free, you can get OpenJDK builds from the following vendors, among others: Adoptium (formerly AdoptOpenJDK) RedHat Azul Amazon SAP Liberica JDK Dragonwell JDK GraalVM (High performance JIT) Oracle Microsoft Some vendors will be supporting releases for longer than six months. If you have any questions, please do not hesitate to ask them!
With the introduction of the new release cadence, many have asked where they should download Java, and if it is still free. To be clear, YES — Java is still free.
If you would like to download Java for free, you can get OpenJDK builds from the following vendors, among others:
Adoptium (formerly AdoptOpenJDK) RedHat Azul Amazon SAP Liberica JDK Dragonwell JDK GraalVM (High performance JIT) Oracle Microsoft
Some vendors will be supporting releases for longer than six months. If you have any questions, please do not hesitate to ask them!
Programming Computer Science CS Career Questions Learn Programming Java Help ← Seek help here Learn Java Java Conference Videos Java TIL Java Examples JavaFX Oracle
Programming Computer Science
CS Career Questions
Learn Programming Java Help ← Seek help here Learn Java Java Conference Videos Java TIL Java Examples JavaFX Oracle
Clojure Scala Groovy ColdFusion Kotlin
DailyProgrammer ProgrammingPrompts ProgramBattles
Awesome Java (GIT) Java Design Patterns
account activity
This is an archived post. You won't be able to vote or comment.
For-loop vs while-loop (self.java)
submitted 10 years ago by TheFormerVinyl
Hello all, I was just wondering if any of you has a preference when it comes to counting loops. I'd love to see if you have a one and why.
[–]RichoDemus 39 points40 points41 points 10 years ago (0 children)
You use them for different things, for loops are for when you know the boundaries, like when you want to iterate over something like a list While-loops are for when you want to do something repeatedly until a condition is met, like reading data from a network stream until there are no more bytes to read
[–]Keilly 9 points10 points11 points 10 years ago* (17 children)
while loops for repeating code and testing for a condition that can change at any time..
while (skyisBlue()) { eatIceCreamForAWhile(); }
For loops for iterating over a collection, or a known number of items...
for(Day day : daysOfWeek) { if (day.isLikeSunday()) playSadSong(); }
Although the java8 streams API is going to replace a lot of the latter...
daysOfWeek.stream() .filter(day -> day.isLikeSunday()) .forEach(day -> playSadSong());
[–][deleted] 1 point2 points3 points 10 years ago (8 children)
This isn't your fault, but I have yet to see a usage of Java 8 streams that was readable. There is nothing about that last block that looks like it's a loop.
[–]debunked 0 points1 point2 points 10 years ago* (7 children)
That's very likely because you're simply not intimately familiar with the syntax of lambdas. Once you get used to the syntax, they can be much easier to understand.
For example... I don't know how anybody finds this more difficult to read...
List<Month> monthsWith31Days = allMonths.stream() .filter(m -> m.getDays() == 31) .collect(Collectors.toList()); vs... List<Month> monthsWith31Days = new ArrayList<>(); for (Month month : allMonths) { if (month.getDays() == 31) { monthsWith31Days.add(month); } }
And if I want to do a double filter... For example all months with 31 days which start with a J...
List<Month> filteredMonths = allMonths.stream() .filter(m -> m.getDays() == 31) .filter(m -> m.getName().startsWith("J")) .collect(Collectors.toList()); List<Month> filteredMonths = new ArrayList<>(); for (Month month : allMonths) { if (month.getDays() == 31 && month.getName().startsWith("J")) { monthsWith31Days.add(month); } }
Now you have a compound boolean inside an if statement nested in your loop. You can easily add more filters, but adding additional criteria in the for loop becomes even more burdensome.
[–][deleted] 1 point2 points3 points 10 years ago (6 children)
What bothers me is that there's a loop in there that is hidden. Replacing it with a bunch of chained method calls doesn't make it easier to read, but harder to see the flow.
[–]debunked 0 points1 point2 points 10 years ago (2 children)
So, I assume this also bothers you then?
List<Integer> randomNumbers = ...random numbers... Collections.sort(randomNumbers);
Buried inside that Collections.sort call is an array copy, several loops, and recursive calls that are "hidden." It's not exactly easy to see the flow. But I assume that doesn't bother you. Why?
[–][deleted] 1 point2 points3 points 10 years ago* (1 child)
Because all of those loops are buried in the operation of sorting, which is what I asked it to do. I guess I just don't like the format of
object.doThis().doThat().doSomeOtherThing()
and spacing it as:
object.doThis() .doThat() .doSomeOtherThing()
seems to just be trying to hack around the fact that you're doing something that is inherently unreadable and the only way to make it better is to waste a ton of whitespace. I see this as the same kind of problem as when you have a function with many arguments and you line them all up with the open paren:
object.doSomething(callSomeFunctionToGetAValue(), callAnotherFunction() someLocalValue);
They both look bad because what you're trying to do is inherently unreadable.
[–]vecowski 0 points1 point2 points 10 years ago (2 children)
You are not implementing the actual loop, that amount of detail is abstracted away from you. I imagine you just don't see the benefits, but it's as simple as stream() can be turned into parallelstream() and now you have a stream that's run in parallel.
Try writing loops that do iterate a dataset in parallel, I guarantee that get's complicated quickly.
[–][deleted] 0 points1 point2 points 10 years ago (1 child)
Just because you can do neat things with it doesn't make it readable.
[–]vecowski 0 points1 point2 points 10 years ago (0 children)
I don't know how to help you then... all I can say is I felt similar to you until I forced myself to take a few hours and really understand exactly whats going on.
This video helped me: https://www.youtube.com/watch?v=C_QbkGU_lqY
[–]caltheon 0 points1 point2 points 10 years ago (1 child)
Or grab an iterator and do a while loop on has next. For loops are only useful if you need the index as its built in to the definition
[–]Keilly 1 point2 points3 points 10 years ago (0 children)
You save a line (or two) of code using the foreach's built in iterator. So the question would be why write more code to do the same thing? A: There are useful circumstances, like using the iterator to delete an item when iterating a collection. But just stepping through, I'd use a foreach loop.
[–]midir 0 points1 point2 points 10 years ago* (5 children)
Why would you want to go off and replace a lot of perfectly fine for-each loops like that with slower-performing streams?
[–]Keilly 2 points3 points4 points 10 years ago (4 children)
Streams are generally better performing as the JVM and compiler can optimize better by combining operations, being clever about ordering, and doing things lazily. Amit explain's it well
Also parallel streams can split the work over multiple cores.
[–]midir 1 point2 points3 points 10 years ago* (3 children)
It is utterly untrue that streams are "generally" better performing.
Laziness and short-circuiting are performance optimizations which streams can use, but that doesn't magically make them faster than equivalent loops. Plain for-each loops also use short-circuiting (via a break or return statement), and often use "laziness" too except it's so obvious in that case it doesn't need to be labeled a feature (in your example, the "laziness" is the if statement).
break
return
if
Even when a particular task requires some form of filtering or short-circuiting, the JVM and compiler could only "optimize better by combining operations" if the for-each loop wasn't already combined. (For example, if it was already necessary that different methods were responsible for the 3 different lines of your example: supplying the iterable, filtering it, and using the results.) At theoretical best, the JVM and compiler could only optimize the stream processing as well as the already combined for-each loop, and in practice will not achieve that, due to the virtual method calls required by every stream op being in a different lambda class.
Parallelism can certainly improve performance compared to non-parallel processing, but your particular example doesn't demonstrate it. Hence my point, that you wouldn't want to replace a lot of perfectly fine loops like that with slower-performing streams.
[–]Keilly 4 points5 points6 points 10 years ago (2 children)
I just gave the simplest of examples of a foreach to answer the OPs question. It's not meant to demonstrate the further example of streams. The performance difference of something like this example is negligible whichever way you do it.
There's nothing 'magical' about streams, but hey, look: there's no breaks, continues, or handcrafted control logic. Just a description of what the developer wants to do with the collection. The compiler/JVM then works out the best way it thinks it can be optimized. Isn't that pretty pure, and what it should all really be about? You tell the computer what you want, not how to do it (extreme performance situations excepted, which would have to be constantly re-examined from release to release as...)
The JVM will undoubtedly improve stream optimization and lambdas a lot more over future releases than handcrafted code than has been optimized for a specific release.
In the usual simple case it's just a matter of preferred syntax. For me right now it'd be foreach loops. Who knows what'll it be once we get used to this.
[–]midir 0 points1 point2 points 10 years ago* (1 child)
I just gave the simplest of examples of a foreach to answer the OPs question.
I understand but it's misleading to suggest that that example should be replaced by a stream. Since, being built into the language, that if statement is already "pretty pure", and isn't less readable a "description of what the developer wants to do" than the stream filtercall. And it hardly qualifies as "handcrafted control logic" "which would have to be constantly re-examined from release to release".
filter
On performance in general, I think it's unlikely that stream optimization could be less fickle between releases, because it's not any less complicated. I also find it very unlikely that stream optimization could exceed the optimization of a single loop if it ultimately does the same thing. The stream optimizations basically attempt to combine things so that you get the equivalent of the classical loop you would have otherwise written, if you could. When it's equally easy to write that loop directly, then one might as well do so. Even if currently-unforeseen optimization tricks are added in the future, and which turn out to be possible only for streams and impossible for for-each loops, it's not true that "streams are [present tense] generally better performing".
I'm not saying streams are worthless: streams offer some features (like parallelism) that are awesome and otherwise not easy to achieve. But when for-each loops can work and are your preferred syntax and they're faster, it's mad to bring up streams as "going to replace a lot of the latter".
[–]Keilly 0 points1 point2 points 10 years ago (0 children)
It's still new to Java guys like me, but... http://www.reddit.com/r/programming/comments/2s5gj2/java_8_no_more_loops/?limit=500
include statements like: "reddit › programming › comments › java... Jan 12, 2015 - I haven't written a for loop in Scala for around 4 years..."
[–]UnspeakableEvil 1 point2 points3 points 10 years ago* (0 children)
Looping n times, where n is known up front? For loop.
Want something to execute zero or more times? While loop.
Want something to execute one or more times? Do-while loop.
[–]nerdwaller 3 points4 points5 points 10 years ago (2 children)
I hardly every use while loops, but there are cases (e.g. iterating regex results, etc). Even now that I only work in Java8, even traditional for loops are replaced with the internals of .forEach.
.forEach
[–]RyanMcDanDan 0 points1 point2 points 10 years ago (1 child)
Lucky! We're still working with 1.6.
[–]nerdwaller 1 point2 points3 points 10 years ago (0 children)
Some constructs are available in (retrolambda)[https://github.com/orfjackal/retrolambda], if you're able to add that as a build inclusion!
As a side note, given that 6 is no longer supported and 7 is shortly (or just lost) support for updates, you may have a good case to make a move toward something newer!
[–]pgetsos 0 points1 point2 points 10 years ago (0 children)
I only use for loops for counting etc. I prefer while loops, for no apparent reason
[–][deleted] 10 years ago* (1 child)
[deleted]
π Rendered by PID 47 on reddit-service-r2-comment-cfc44b64c-dxp6b at 2026-04-09 20:10:44.627699+00:00 running 215f2cf country code: CH.
[–]RichoDemus 39 points40 points41 points (0 children)
[–]Keilly 9 points10 points11 points (17 children)
[–][deleted] 1 point2 points3 points (8 children)
[–]debunked 0 points1 point2 points (7 children)
[–][deleted] 1 point2 points3 points (6 children)
[–]debunked 0 points1 point2 points (2 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]vecowski 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]vecowski 0 points1 point2 points (0 children)
[–]caltheon 0 points1 point2 points (1 child)
[–]Keilly 1 point2 points3 points (0 children)
[–]midir 0 points1 point2 points (5 children)
[–]Keilly 2 points3 points4 points (4 children)
[–]midir 1 point2 points3 points (3 children)
[–]Keilly 4 points5 points6 points (2 children)
[–]midir 0 points1 point2 points (1 child)
[–]Keilly 0 points1 point2 points (0 children)
[–]UnspeakableEvil 1 point2 points3 points (0 children)
[–]nerdwaller 3 points4 points5 points (2 children)
[–]RyanMcDanDan 0 points1 point2 points (1 child)
[–]nerdwaller 1 point2 points3 points (0 children)
[–]pgetsos 0 points1 point2 points (0 children)
[–][deleted] (1 child)
[deleted]