Run for-each loop just one time - java

I have this following loop and I want to run it for just one time.
how can I do that?
for (AnnotationData annotations : annotation)

A loop that runs once isn't much of a loop.
If annotations is an array, get the first one using annotations[0]. If it's a List, do annotations.get(0). Otherwise, do annotations.iterator().next(). If you're not sure if the collection has at least one element, make sure to check that first.
This will be clearer, since when people see a for they usually expect a loop. One that actually, well, loops.

Just break out!
for (AnnotationData annotation : annotations) {
// do something with "annotation"
break; // only execute loop body once
}
Other answers are using counters or flags!? It never ceases to amaze me just how much code some people write to do the simplest of things. Typically, the more inferior the programmer, the more code they write.
Edited:
There is a misunderstanding by some commenters that a non-loop version would use "less code" or "less lines". Such claims are untrue... here is the precise non-loop equivalent code:
if (!annotations.isEmpty()) {
AnnotationData annotation = annotations.get(0);
// do something with "annotation"
}
This uses the same number of lines, but requires 23 more characters of code, although I grant you its intention is more emphatic.

There is no need for any counter. Simply add a break in the end as:
for (AnnotationData annotations : annotation){
//your all code
break;
}

int i=0;
for (AnnotationData annotations : annotation){
if(i==1)
{
break;
}
i++;
}

Related

Strange "for(;;)" infinite loop in Java, how is this useful? [duplicate]

This question already has answers here:
How does a for loop work, specifically for(;;)?
(6 answers)
Closed 7 years ago.
Though I have some experience in Java, the following code looks a bit strange to me:
public class ForLoopTest{
public static void main(String[] args){
for(;;){}
}
}
This code compiles fine, although the initialization-test-increment part is empty, unlike a usual for loop:
for(int i=0; i<10; i++){}
Since the code compiles fine, it's valid syntax.
Is there any practical use of this type of for loop where there is no initialization-test-increment part ?
It's equivalent to while(true) {}.
There's no real reason to use or not to use a for loop that way (and it's not often that you would write a while(true) loop either).
This is one way of writing an infinite loop. It's equivalent to:
while(true){ }
Or:
boolean loop = true;
while (loop) {
//do nothing
}
Or even:
int theAnswerToTheQuestionOfLifeTheUniverseAndEverything = 42;
while(theAnswerToTheQuestionOfLifeTheUniverseAndEverything == 42) {
//do nothing
}
​​​​​​​​​​​​​​​​​​​​​​​​
It is an infinite loop. The way you can use it (without being an infinite loop) would be like this (you will probably never use this way):
int i = 0;
for(;;) {
if(i == 10) {
break;
}
i++;
}
Your loop for(;;){} is equivalent to while(true) {}
Yes, it is an inifinite loop.
If your question is: There are any reason to use that?
The answer is maybe yes.
I'll give you an example:
What if you want to do a program that read measurements from time to time continuously?
like a monitor showing you what does a dron recording or something similar?
You will may need a loop like this to refresh the image.
But yes, usually you don't need that for anything.
Kayaman is correct. A loop in that format will need to have some exit condition within it, or it will undoubtedly be an infinite loop. Most people use while(true) in this case since it's easier to understand. I had a prof once tell me that the only advantage of for(;;) {} is that it looks more impressive than while(true).
for(;;) is equivalent to while(true). The reason you see the former more often in code is, that it is the canonical way of encoding an endless loop in the C programming language from where Java borrowed a lot of syntactical elements and which is the background of a lot of Java developers.
Using while(true) might look more straight-forward, but the C programming language had no boolean types nor true literal in the beginning, so the equivalent had to be while(1) then, which doesn’t look better than for(;;). It helped the latter to become a common pattern as it was specified by K&R (see this answer) as the idiom for an eternal loop.
Well, and changing the programming language doesn’t necessarily imply changing habits, so you see for(;;) in Java now almost as often as in C.
As Kayaman also mentioned it's equivalent to while(true) {}.
One use case I can think of is - if you need to do some operation as soon as a semaphore file arrives in a directory. You can keep checking file arrival in an infinite loop, as soon as file arrives then do some operation and break the loop

Java for-loop, do i need continue statement here?

Consider this code:
if (int a == 0) {
System.out.println("hello");
continue;
}
This if is part of a for loop in java. What is the significane of continue statement here? I know continue is the opposite of break so that it wont break out of the loop rather just skip that iteration for anything below it. But in case it is inside an if statement, do I really need it like this?
No, you don't need to use continue there, you can use an else block instead:
if (a == 0) {
System.out.println("hello");
} else {
// The rest of the loop body goes here.
}
Which is better is a style issue. Sometimes one is better, sometimes the other - it depends on what the typical flow should be and which flow you want to emphasize in the code.
If this is the last statement of the for loop - no, you don't need it. Otherwise you need it to skip everything below the if-clause. If you don't want to skip it, then don't use continue.
Here is an explanation with examples of what continue is doing.
continue means that the statements below the if block won't work. If this is the behavior you need, you should continue. Otherwise it is not needed.

How do I break multiple foreach loops? [duplicate]

This question already has answers here:
How do I break out of nested loops in Java?
(37 answers)
Closed 5 years ago.
I have four foreach loops that iterate through the collections and based on a condition do something.
Here is the code that I am writing now:
boolean breakFlag = false;
String valueFromObj2 = null;
String valueFromObj4 = null;
for(Object1 object1: objects){
for(Object2 object2: object1){
// I get some value from object2
valueFromObj2 = object2.getSomeValue();
for(Object3 object3 : object2){
for(Object4 object4: object3){
// Finally I get some value from Object4.
valueFromObj4 = object4.getSomeValue();
// Compare with valueFromObj2 to decide either to break all the foreach loop
breakFlag = compareTwoVariable(valueFromObj2, valueFromObj4 );
if(breakFlag){break;}
} // fourth loop ends here
if(breakFlag){break;}
} // third loop ends here
if(breakFlag){break;}
} // second loop ends here
if(breakFlag){break;}
} // first loop ends here
The main object (objects in the code) comes from a third-party provider SDK, so I cannot change anything on that portion. I want to ask the Stack Overflow community if there is a better approach to break all the four foreach loops. Or if there is any other way to refactor this code to make it more readable and maintainable.
Use a label on the outermost loop, and include this label in the break statement when you want to jump out of all the loops. In the example below, I've modified your code to use the label OUTERMOST:
String valueFromObj2 = null;
String valueFromObj4 = null;
OUTERMOST: for(Object1 object1: objects){
for(Object2 object2: object1){
//I get some value from object2
valueFromObj2 = object2.getSomeValue();
for(Object3 object3 : object2){
for(Object4 object4: object3){
//Finally I get some value from Object4.
valueFromObj4 = object4.getSomeValue();
//Compare with valueFromObj2 to decide either to break all the foreach loop
if( compareTwoVariable(valueFromObj2, valueFromObj4 )) {
break OUTERMOST;
}
}//fourth loop ends here
}//third loop ends here
}//second loop ends here
}//first loop ends here
Extract all the loops into the function and use return.
You could use a labeled break statement.
This kind of break terminates an outer statement
See The break Statement
See the Branching Statements Java Tutorial for the easiest way, using a label. You can label any or all of the for loops, then use break or continue in conjunction with those labels.
An alternative to using labels is to use return instead. Just refactor your code into a method call to bypass the need to use labels at all.
Your example is rather generic so it's hard to say what's going on but I'm getting such a a strong code smell from the code you provided that I'm forced to think there has to be another way to do the thing entirely, most likely through refactoring the actual data structure to something more meaningful.
What kind of list objects is? What other (most likely important) data it contains? If it's not too much of a hassle, I'd appreciate if you provided more relevant code since the refactorer in me is getting all giddy just from seeing that pile of loops.
One way to break, or collapse several statements (actually stack frames) is to throw an exception but this is not recommended because it really expensive for the run-time to unwind the stack and it could lead to really nasty difficult to debug undefined behavior, (keep this in mind).
Otherwise, what I recommend, rewrite that code to be able to break out of the loop in a graceful manner. If you cant change this code in any other way, well then you'll have to result to exceptions...
Throw an exception and catch it outside the loops? Use something that's "considered harmful?"
It's a bit funny when computer science paints itself into a corner ;-)
The straightforward solution is to put the entire search process in a method and return as soon as you have an answer.
However, the abstract form of your sample code leaves some other possibilities in question. For instance, is there a way to "index" some of the content (e.g. using Map instances) so that you don't have to use brute-force loops?
Apart from the fact that Java supports labelled break, see also Is it possible to exit a for before time in C++, if an ending condition is reached? which is a similar question with some other relevent solutions.

Iterate with for loop or while loop?

I often see code like:
Iterator i = list.iterator();
while(i.hasNext()) {
...
}
but I write that (when Java 1.5 isn't available or for each can't be used) as:
for(Iterator i = list.iterator(); i.hasNext(); ) {
...
}
because
It is shorter
It keeps i in a smaller scope
It reduces the chance of confusion. (Is i used outside the
while? Where is i declared?)
I think code should be as simple to understand as possible so that I only have to make complex code to do complex things. What do you think? Which is better?
From: http://jamesjava.blogspot.com/2006/04/iterating.html
I prefer the for loop because it also sets the scope of the iterator to just the for loop.
There are appropriate uses for the while, the for, and the foreach constructs:
while - Use this if you are iterating and the deciding factor for looping or not is based merely on a condition. In this loop construct, keeping an index is only a secondary concern; everything should be based on the condition
for - Use this if you are looping and your primary concern is the index of the array/collection/list. It is more useful to use a for if you are most likely to go through all the elements anyway, and in a particular order (e.g., going backwards through a sorted list, for example).
foreach - Use this if you merely need to go through your collection regardless of order.
Obviously there are exceptions to the above, but that's the general rule I use when deciding to use which. That being said I tend to use foreach more often.
Why not use the for-each construct? (I haven't used Java in a while, but this exists in C# and I'm pretty sure Java 1.5 has this too):
List<String> names = new ArrayList<String>();
names.add("a");
names.add("b");
names.add("c");
for (String name : names)
System.out.println(name.charAt(0));
I think scope is the biggest issue here, as you have pointed out.
In the "while" example, the iterator is declared outside the loop, so it will continue to exist after the loop is done. This may cause issues if this same iterator is used again at some later point. E. g. you may forget to initialize it before using it in another loop.
In the "for" example, the iterator is declared inside the loop, so its scope is limited to the loop. If you try to use it after the loop, you will get a compiler error.
if you're only going to use the iterator once and throw it away, the second form is preferred; otherwise you must use the first form
IMHO, the for loop is less readable in this scenario, if you look at this code from the perspective of English language. I am working on a code where author does abuse for loop, and it ain't pretty. Compare following:
for (; (currUserObjectIndex < _domainObjectReferences.Length) && (_domainObjectReferences[currUserObjectIndex].VisualIndex == index); ++currUserObjectIndex)
++currNumUserObjects;
vs
while (currUserObjectIndex < _domainObjectReferences.Length && _domainObjectReferences[currUserObjectIndex].VisualIndex == index)
{
++currNumUserObjects;
++currUserObjectIndex;
}
I would agree that the "for" loop is clearer and more appropriate when iterating.
The "while" loop is appropriate for polling, or where the number of loops to meet exit condition will change based on activity inside the loop.
Not that it probably matters in this case, but Compilers, VMs and CPU's normally have special optimization techniques they user under the hood that will make for loops performance better (and in the near future parallel), in general they don't do that with while loops (because its harder to determine how it's actually going to run). But in most cases code clarity should trump optimization.
Using for loop you can work with a single variable, as it sets the scope of variable for a current working for loop only. However this is not possible in while loop.
For Example:
int i; for(i=0; in1;i++) do something..
for(i=0;i n2;i+=2) do something.
So after 1st loop i=n1-1 at the end. But while using second loop you can set i again to 0.
However
int i=0;
while(i less than limit) { do something ..; i++; }
Hence i is set to limit-1 at the end. So you cant use same i in another while loop.
Either is fine. I use for () myself, and I don't know if there are compile issues. I suspect they both get optimized down to pretty much the same thing.
I agree that the for loop should be used whenever possible but sometimes there's more complex logic that controls the iterator in the body of the loop. In that case you have to go with while.
I was the for loop for clarity. While I use the while loop when faced with some undeterministic condition.
Both are fine, but remember that sometimes access to the Iterator directly is useful (such as if you are removing elements that match a certain condition - you will get a ConcurrentModificationException if you do collection.remove(o) inside a for(T o : collection) loop).
I prefer to write the for(blah : blah) [foreach] syntax almost all of the time because it seems more naturally readable to me. The concept of iterators in general don't really have parallels outside of programming
Academia tends to prefer the while-loop as it makes for less complicated reasoning about programs. I tend to prefer the for- or foreach-loop structures as they make for easier-to-read code.
Although both are really fine, I tend to use the first example because it is easier to read.
There are fewer operations happening on each line with the while() loop, making the code easier for someone new to the code to understand what's going on.
That type of construct also allows me to group initializations in a common location (at the top of the method) which also simplifies commenting for me, and conceptualization for someone reading it for the first time.

Should I avoid using Java Label Statements?

Today I had a coworker suggest I refactor my code to use a label statement to control flow through 2 nested for loops I had created. I've never used them before because personally I think they decrease the readability of a program. I am willing to change my mind about using them if the argument is solid enough however. What are people's opinions on label statements?
Many algorithms are expressed more easily if you can jump across two loops (or a loop containing a switch statement). Don't feel bad about it. On the other hand, it may indicate an overly complex solution. So stand back and look at the problem.
Some people prefer a "single entry, single exit" approach to all loops. That is to say avoiding break (and continue) and early return for loops altogether. This may result in some duplicate code.
What I would strongly avoid doing is introducing auxilary variables. Hiding control-flow within state adds to confusion.
Splitting labeled loops into two methods may well be difficult. Exceptions are probably too heavyweight. Try a single entry, single exit approach.
Labels are like goto's: Use them sparingly, and only when they make your code faster and more importantly, more understandable,
e.g., If you are in big loops six levels deep and you encounter a condition that makes the rest of the loop pointless to complete, there's no sense in having 6 extra trap doors in your condition statements to exit out the loop early.
Labels (and goto's) aren't evil, it's just that sometimes people use them in bad ways. Most of the time we are actually trying to write our code so it is understandable for you and the next programmer who comes along. Making it uber-fast is a secondary concern (be wary of premature optimization).
When Labels (and goto's) are misused they make the code less readable, which causes grief for you and the next developer. The compiler doesn't care.
There are few occasions when you need labels and they can be confusing because they are rarely used. However if you need to use one then use one.
BTW: this compiles and runs.
class MyFirstJavaProg {
public static void main(String args[]) {
http://www.javacoffeebreak.com/java101/java101.html
System.out.println("Hello World!");
}
}
I'm curious to hear what your alternative to labels is. I think this is pretty much going to boil down to the argument of "return as early as possible" vs. "use a variable to hold the return value, and only return at the end."
Labels are pretty standard when you have nested loops. The only way they really decrease readability is when another developer has never seen them before and doesn't understand what they mean.
I have use a Java labeled loop for an implementation of a Sieve method to find prime numbers (done for one of the project Euler math problems) which made it 10x faster compared to nested loops. Eg if(certain condition) go back to outer loop.
private static void testByFactoring() {
primes: for (int ctr = 0; ctr < m_toFactor.length; ctr++) {
int toTest = m_toFactor[ctr];
for (int ctr2 = 0; ctr2 < m_divisors.length; ctr2++) {
// max (int) Math.sqrt(m_numberToTest) + 1 iterations
if (toTest != m_divisors[ctr2]
&& toTest % m_divisors[ctr2] == 0) {
continue primes;
}
} // end of the divisor loop
} // end of primes loop
} // method
I asked a C++ programmer how bad labeled loops are, he said he would use them sparingly, but they can occasionally come in handy. For example, if you have 3 nested loops and for certain conditions you want to go back to the outermost loop.
So they have their uses, it depends on the problem you were trying to solve.
I've never seen labels used "in the wild" in Java code. If you really want to break across nested loops, see if you can refactor your method so that an early return statement does what you want.
Technically, I guess there's not much difference between an early return and a label. Practically, though, almost every Java developer has seen an early return and knows what it does. I'd guess many developers would at least be surprised by a label, and probably be confused.
I was taught the single entry / single exit orthodoxy in school, but I've since come to appreciate early return statements and breaking out of loops as a way to simplify code and make it clearer.
I'd argue in favour of them in some locations, I found them particularly useful in this example:
nextItem: for(CartItem item : user.getCart()) {
nextCondition : for(PurchaseCondition cond : item.getConditions()) {
if(!cond.check())
continue nextItem;
else
continue nextCondition;
}
purchasedItems.add(item);
}
I think with the new for-each loop, the label can be really clear.
For example:
sentence: for(Sentence sentence: paragraph) {
for(String word: sentence) {
// do something
if(isDone()) {
continue sentence;
}
}
}
I think that looks really clear by having your label the same as your variable in the new for-each. In fact, maybe Java should be evil and add implicit labels for-each variables heh
I never use labels in my code. I prefer to create a guard and initialize it to null or other unusual value. This guard is often a result object. I haven't seen any of my coworkers using labels, nor found any in our repository. It really depends on your style of coding. In my opinion using labels would decrease the readability as it's not a common construct and usually it's not used in Java.
Yes, you should avoid using label unless there's a specific reason to use them (the example of it simplifying implementation of an algorithm is pertinent). In such a case I would advise adding sufficient comments or other documentation to explain the reasoning behind it so that someone doesn't come along later and mangle it out of some notion of "improving the code" or "getting rid of code smell" or some other potentially BS excuse.
I would equate this sort of question with deciding when one should or shouldn't use the ternary if. The chief rationale being that it can impede readability and unless the programmer is very careful to name things in a reasonable way then use of conventions such as labels might make things a lot worse. Suppose the example using 'nextCondition' and 'nextItem' had used 'loop1' and 'loop2' for his label names.
Personally labels are one of those features that don't make a lot of sense to me, outside of Assembly or BASIC and other similarly limited languages. Java has plenty of more conventional/regular loop and control constructs.
I found labels to be sometimes useful in tests, to separate the usual setup, excercise and verify phases and group related statements. For example, using the BDD terminology:
#Test
public void should_Clear_Cached_Element() throws Exception {
given: {
elementStream = defaultStream();
elementStream.readElement();
Assume.assumeNotNull(elementStream.lastRead());
}
when:
elementStream.clearLast();
then:
assertThat(elementStream.lastRead()).isEmpty();
}
Your formatting choices may vary but the core idea is that labels, in this case, provide a noticeable distinction between the logical sections comprising your test, better than comments can. I think the Spock library just builds on this very feature to declare its test phases.
Personally whenever I need to use nested loops with the innermost one having to break out of all the parent loops, I just write everything in a method with a return statement when my condition is met, it's far more readable and logical.
Example Using method:
private static boolean exists(int[][] array, int searchFor) {
for (int[] nums : array) {
for (int num : nums) {
if (num == searchFor) {
return true;
}
}
}
return false;
}
Example Using label (less readable imo):
boolean exists = false;
existenceLoop:
for (int[] nums : array) {
for (int num : nums) {
if (num == searchFor) {
exists = true;
break existenceLoop;
}
}
}
return exists;

Categories

Resources