Monday, June 1, 2020

Loop

For-Each Loop

Java 5 introduced an for-each loop, which is called a enhanced for each loop. It is used to iterate over elements of an array and the collection.
The syntax of Java for-each loop consists of data_type with the variable followed by a colon (:), then array or collection.

Syntax

for(data_type item : array | collection){
//body of for-each loop
}
Here,
collection - a collection or array that you have to loop through.
item - a single item from the collection.

For-each loop Example: Traversing the array elements

/An example of Java for-each loop
class ForEachExample1{
public static void main(String args[]){
//declaring an array
int arr[]={12,13,14,44};
//traversing the array with for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Output:
12

13

14

44

For-each loop Example: Traversing the collection elements

import java.util.*;
class ForEachExample2{
public static void main(String args[]){
//Creating a list of elements
ArrayList<String> list=new ArrayList<String>();
list.add("vimal");
list.add("sonoo");
list.add("ratan");
//traversing the list of elements using for-each loop
for(String s:list){
System.out.println(s);
}
}
}
for(String s:list)
Read as for each String s in list

Output:

vimal
sonoo
ratan

package com.cerotid.fundamentals;
import java.util.ArrayList;
import java.util.List;
public class ForEachDemo {
public static void main(String[] args) {
// creating a list of elements
List<String> gameList = new ArrayList<String>();
gameList.add("football");
gameList.add("volleyball");
gameList.add("kapardi");
gameList.add("ludo");
// traversing the list of elements
System.out.println("........Iterating by using for loop...........");
for (String s : gameList) {
System.out.println(s);
}
System.out.println("------------Iterating by passing lambda expression--------------");
gameList.forEach(games -> System.out.println(games));
System.out.println("............Iterating by passing method reference..........");
gameList.forEach(System.out::println);
// Java Stream forEachOrdered() Method Example
// Along with forEach() method, Java provides one more method forEachOrdered().
// It is used to iterate elements in the order specified by the stream.
System.out.println(".........Iterating by passing lamda expression.............");
gameList.stream().forEach(games -> System.out.println(games));
}
}
Output:
........Iterating by using for loop...........
football
volleyball
kapardi
ludo
------------Iterating by passing lambda expression--------------
football
volleyball
kapardi
ludo
............Iterating by passing method reference..........
football
volleyball
kapardi
ludo
.........Iterating by passing lamda expression.............
football
volleyball
kapardi
ludo

4.1. Iterating over a Collection


Any iterable of type Collection – list, set, queue etc. have the same syntax for using forEach.

Therefore, as we have already seen, to iterate elements of a list:

1
2
3
List<String> names = Arrays.asList("Larry", "Steve", "James");
names.forEach(System.out::println);
Similarly for a set:

1
2
3
Set<String> uniqueNames = new HashSet<>(Arrays.asList("Larry", "Steve", "James"));
uniqueNames.forEach(System.out::println);
Or let's say for a Queue which is also a Collection:

1
2
3
Queue<String> namesQueue = new ArrayDeque<>(Arrays.asList("Larry", "Steve", "James"));
namesQueue.forEach(System.out::println);
Reference:

7 ways to iterate through list:
package com.cerotid.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class IterateThroughLoop {
public static void main(String[] args) {
// create list
List<String> list = new ArrayList<String>();
// add 4 different values to list
list.add("Facebook");
list.add("Yahoo");
list.add("Google");
list.add("YouTube");
// simple for loop
System.out.println("1......using simeple for loop...........");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
// enhanced for loop
System.out.println("2......using enhanced for looop.......");
for (String socialMediaNames : list) {
System.out.println(socialMediaNames);
}
// Iterator - Returns an iterator over the elements in this list in proper sequence.
System.out.println("3......using Iterator........");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// ListIterator - traverse a list of elements in either forward or backward order
// An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration,
// and obtain the iterator's current position in the list.
System.out.println("4.......using listIterator.........");
ListIterator<String> listIterator = list.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
// while loop
System.out.println("5.....using while loop......");
int i = 0;
while (i < list.size()) {
System.out.println(list.get(i));
i++;
}
// Iterating by passing lambda expression
System.out.println("6.....passing Lambda expression ......");
list.forEach(Template -> System.out.println(Template));
// stream.forEach()
System.out.println("7.....uisng stream.forEach()........");
list.stream().forEach(action -> System.out.println(action));
}
}
Output:
1......using simeple for loop...........
Facebook
Yahoo
Google
YouTube
2......using enhanced for looop.......
Facebook
Yahoo
Google
YouTube
3......using Iterator........
Facebook
Yahoo
Google
YouTube
4.......using listIterator.........
Facebook
Yahoo
Google
YouTube
5.....using while loop......
Facebook
Yahoo
Google
YouTube
6.....using Iterable.forEach().......
Facebook
Yahoo
Google
YouTube
7.....uisng stream.forEach()........
Facebook
Yahoo
Google
YouTube

No comments:

Post a Comment