Using a stream to iterate n times instead of using a for loop to create n items
You could use Stream#generate with limit: Stream.generate(MyClass::new).limit(10);
You could use Stream#generate with limit: Stream.generate(MyClass::new).limit(10);
You are using USCOUNTER in a subshell, that’s why the variable is not showing in the main shell. Instead of cat FILE | while …, do just a while … done < $FILE. This way, you avoid the common problem of I set variables in a loop that’s in a pipeline. Why do they disappear …
Use a timer. There are 3 basic kinds, each suited for different purposes. System.Windows.Forms.Timer Use only in a Windows Form application. This timer is processed as part of the message loop, so the the timer can be frozen under high load. System.Timers.Timer When you need synchronicity, use this one. This means that the tick event …
You can use eachWithIndex: list.eachWithIndex { item, index -> println item println index } With Groovy 2.4 and newer, you can also use the indexed() method. This can be handy to access the index with methods like collect: def result = list.indexed().collect { index, item -> “$index: $item” } println result
Consider throw/catch. Normally the outside loop in the below code will run five times, but with throw you can change it to whatever you like, breaking it in the process. Consider this perfectly valid ruby code: catch (:done) do 5.times { |i| 5.times { |j| puts “#{i} #{j}” throw :done if i + j > …
The <c:forEach> tag is definitely suitable for this. It has begin and end attributes where you can specify the, well, begin and end. It has a varStatus attribute which puts a LoopTagStatus object in the loop tag scope which in turn has several methods like getIndex() and on. Here’s a kickoff example: <c:forEach begin=”0″ end=”10″ …
String#each_line str.each_line do |line| #do something with line end
WARNING: Long(ish) Answer This is copied directly from an article I wrote in an internal company wiki: Question: How to properly use closures in loops? Quick answer: Use a function factory. for (var i=0; i<10; i++) { document.getElementById(i).onclick = (function(x){ return function(){ alert(x); } })(i); } or the more easily readable version: function generateMyHandler (x) …
Is it the correct way to use while loops with asynchronous conditions? Yes. async functions simply suspend their execution on every await until the respective promises fulfills, and any control structures continue to work as before.
The idiom (shared by quite a few other languages) for an unused variable is a single underscore _. Code analysers typically won’t complain about _ being unused, and programmers will instantly know it’s a shortcut for i_dont_care_wtf_you_put_here. There is no way to iterate without having an item variable – as the Zen of Python puts …