Showing posts with label loop. Show all posts
Showing posts with label loop. Show all posts

Saturday, 10 September 2022

How to break out of nested loops in Java?

In this post, I am going to explain how to break the outer loop in Java.

 

Approach 1: Using labelled break statement.

 

labelled break

label is a group of statements, identified by using labelname.

 

Syntax

labelName: {
      statement 1
      statement 2
      …....
      statement N
    }

 

Syntax to break the label

break labelName;

 

BreakOuterLoopDemo1.java

package com.sample.app.loops;

public class BreakOuterLoopDemo1 {

	public static void main(String[] args) {
		outerLoop: 
			for (int i = 1; i < 10; i++) {
				for (int j = 1; j < 10; j++) {
					if (i * j > 5) {
						System.out.println("Breaking outer loop");
						break outerLoop;
					} else {
						System.out.println("(" + i + "," + j + ")");
					}
				}
				System.out.println("Inner loop executed....");
			}
	}

}

 

Output

(1,1)
(1,2)
(1,3)
(1,4)
(1,5)
Breaking outer loop

 

Approach 2: Keep the looping logic in a different method, and return from the method, when you meet the criteria.

 

BreakOuterLoopDemo2.java

package com.sample.app.loops;

public class BreakOuterLoopDemo2 {

	public static void doSomeLogic() {
		for (int i = 1; i < 10; i++) {
			for (int j = 1; j < 10; j++) {
				if (i * j > 5) {
					System.out.println("Breaking outer loop");
					return;
				} else {
					System.out.println("(" + i + "," + j + ")");
				}
			}
			System.out.println("Inner loop executed....");
		}
	}

	public static void main(String[] args) {
		doSomeLogic();
	}

}

 

Output

(1,1)
(1,2)
(1,3)
(1,4)
(1,5)
Breaking outer loop

 

Approach 3: With the help of a Boolean flag.

 

BreakOuterLoopDemo3.java

package com.sample.app.loops;

public class BreakOuterLoopDemo3 {

	public static void main(String[] args) {
		boolean flag = true;

		for (int i = 1; (i < 10 && flag); i++) {
			for (int j = 1; (j < 10 && flag); j++) {
				if (i * j > 5) {
					System.out.println("Breaking outer loop");
					flag = false;
				} else {
					System.out.println("(" + i + "," + j + ")");
				}
			}
			System.out.println("Inner loop executed....");
		}
	}

}

 

Output

(1,1)
(1,2)
(1,3)
(1,4)
(1,5)
Breaking outer loop
Inner loop executed....

 


 
 

You may like

Interview Questions

Extract the elements of specific type in a collection

Method overloading ambiguity with null values in Java

Quick guide to load balancers

Constant folding in Java

Quick guide to assertions in Java

java.util.Date vs java.sql.Date

Monday, 16 May 2022

How for-each or enhanced for loop works in Java?

In this post, I am going to explain about for-each loop.

 

‘for-each’ is an enhanced version of for loop and provides a cleaner way to iterate over collections and arrays.

 

Let’s get comfortable by practising some examples.

 

Iterate over an array using for-each loop

Syntax

for (DataType ele : array) { 
    .....
    .....
}

 

Above snippet is equivalent to below ‘for’ loop version.

for (int i=0; i<arr.length; i++) 
{ 
    DataType ele = arr[i];
    .......
    .......
}

 

IterateOverArrayUsingForEachLoop.java

package com.sample.app;

public class IterateOverArrayUsingForEachLoop {

	public static void main(String[] args) {
		int[] arr = { 2, 3, 5, 7 };

		for (int ele : arr) {
			System.out.println(ele);
		}
	}

}

 

Output

2
3
5
7

 

Iterate over an List using for-each loop

Syntax

 

for (DataType ele : list) { 
    .....
    .....
}

 

Above snippet is equivalent to below ‘for’ loop version.

for(int i = 0; i < list.size(); i++) {
	DataType ele = list.get(i);
	......
	......
}

Find the below working application.

 

IterateOverListUsingForEachLoop.java

package com.sample.app;

import java.util.Arrays;
import java.util.List;

public class IterateOverListUsingForEachLoop {
	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(2, 3, 5, 7);
		
		for(Integer ele: list) {
			System.out.println(ele);
		}
		
		for(int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}
	}
}

Iterate over a map using for-each loop

Syntax

for(DataType key: map.keySet()) {
	DataType valye = map.get(key);
	.....
	.....
}

Find the below working application.

 

IterateOverAMapUsingForEachLoop.java

package com.sample.app;

import java.util.HashMap;
import java.util.Map;

public class IterateOverAMapUsingForEachLoop {
	
	public static void main(String[] args) {
		Map<Integer, String> numbersMap = new HashMap<>();
		
		numbersMap.put(1, "One");
		numbersMap.put(2, "Two");
		numbersMap.put(3, "Three");
		
		for(Integer key: numbersMap.keySet()) {
			System.out.printf("%d --> %s\n", key, numbersMap.get(key));
		}
	}

}

Output

1 --> One
2 --> Two
3 --> Three

You can refer this post, to find different ways to iterate over a map using for-each loop.

 

Can I provide for-each behaviour to custom collection?

By implementing Iterable interface, we can provide for-each behaviour to a custom collection.

 

EvenIndicesList.java

package com.sample.app;

import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class EvenIndicesList<T> implements Iterable<T> {
	private List<T> list;

	EvenIndicesList(List<T> list) {
		this.list = list;
	}

	public Iterator<T> iterator() {
		return new EvenIterator<T>();
	}

	@SuppressWarnings("hiding")
	private class EvenIterator<T> implements Iterator<T> {
		int size = list.size();
		int currentPointer = 0;

		public boolean hasNext() {
			return (currentPointer < size);
		}

		public T next() {
			if (!hasNext()) {
				throw new NoSuchElementException();
			}

			@SuppressWarnings("unchecked")
			T val = (T) list.get(currentPointer);
			currentPointer += 2;

			return val;
		}

	}

}

‘EvenIndicesList’ class print the elements at even indexes while iterate using for-each loop. Let’s test this behaviour.

 

TestEvenList.java

package com.sample.app;

import java.util.Arrays;
import java.util.List;

public class TestEvenList {
	public static void main(String args[]) {
		List<Integer> list = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19);

		EvenIndicesList<Integer> myList = new EvenIndicesList(list);

		for (int i : myList) {
			System.out.println(i);
		}
	}
}

Output

2
5
11
17


 

 You may like

Interview Questions

Jagged arrays in Java

Get the length of longest row in a two dimensional jagged array in Java

Quick guide to OutOfMemoryError in Java

StackOverFlowError vs OutOfMemoryError in Java

Different ways to iterate over a map using for-each loop

Different ways to iterate over a map using for-each loop

In this post, I am going explain the two approaches to iterate over a map using for-each loop.

 

Approach 1: for-each loop with Map entrySet

for (Map.Entry<Integer, String> entry : numbersMap.entrySet()) {
	System.out.printf("%d --> %s\n", entry.getKey(), entry.getValue());
}

 

Approach 2L for-each loop with Map keyset.

for (Integer key : numbersMap.keySet()) {
	System.out.printf("%d --> %s\n", key, numbersMap.get(key));
}

 

Find the below working application.

 

ForEachMapDemo.java

package com.sample.app;

import java.util.HashMap;
import java.util.Map;

public class ForEachMapDemo {

	public static void main(String[] args) {
		Map<Integer, String> numbersMap = new HashMap<>();

		numbersMap.put(1, "One");
		numbersMap.put(2, "Two");
		numbersMap.put(3, "Three");

		// Approach 1
		for (Map.Entry<Integer, String> entry : numbersMap.entrySet()) {
			System.out.printf("%d --> %s\n", entry.getKey(), entry.getValue());
		}

		System.out.println("\n\n");

		// Approach 2
		for (Integer key : numbersMap.keySet()) {
			System.out.printf("%d --> %s\n", key, numbersMap.get(key));
		}
	}

}

 

Output

1 --> One
2 --> Two
3 --> Three



1 --> One
2 --> Two
3 --> Three

   

 You may like

Interview Questions

How to resolve NoClassDefFoundError?

Jagged arrays in Java

Get the length of longest row in a two dimensional jagged array in Java

Quick guide to OutOfMemoryError in Java

StackOverFlowError vs OutOfMemoryError in Java