Friday, November 1, 2019

5 Examples Of Enhanced For Loop Inward Java

Enhanced for loop was added way dorsum inwards 2004 inwards Java as well as it provides an slowly as well as cleaner way to iterate over array as well as Collection inwards Java. The introduction of forEach() inwards Java 8 has farther improved iteration but that doesn't hateful that you lot need to forget the for each loop. In this article, you'll run across approximately cool examples of enhanced for loop inwards Java which volition attention you lot to write improve as well as to a greater extent than readable code inwards Java. It's likewise less error-prone because you lot don't convey to bargain alongside an index similar you lot need to alongside the classic "for" loop. This agency no risk of one-off error, agency no risk of starting alongside index zero when you lot desire to start alongside 1 or vice-versa.

Though similar other for loop it likewise has approximately constraints as well as restrictions similar you lot cannot withdraw elements during iteration, for that you lot need to purpose the Iterator.

Another limitation of enhanced "for" loop is that you lot cannot acquire back, agency you lot tin flame start from the concluding chemical ingredient as well as acquire dorsum towards the commencement element. This is possible inwards traditional "for" loop because you lot convey access to the index.


Syntax of The Enhanced "for" Loop

If you lot are wondering how is the enhanced "for" loop looks similar as well as what is the syntax to purpose it, hither is an icon from Cay S. Horstmann's Core Java Book Chapter 7, which clearly explains the syntax of enhanced for loop inwards Java:

 Enhanced for loop was added way dorsum inwards  5 Examples of Enhanced for loop inwards Java

You tin flame run across that you lot simply need to declare a variable of the type your Collection holds as well as you lot are done.

Pros of enhanced for loop
1. Cleaner code, slowly to write as well as read
2. No risk of one-off error

Cons of enhanced for loop
1. You cannot remove() elements during iteration.
2. You cannot acquire backward during traversal, it e'er from commencement to last

And, if you lot desire to larn to a greater extent than close enhanced for loop concepts, you lot tin flame see The Complete Java MasterClass course on Udemy. One of the most comprehensive as well as up-to-date class to larn Java fundamentals.


Enhanced for loop Examples inwards Java

Here are 5 examples of enhanced for loop inwards Java

import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List;   public class Main {     public static void main(String args[]) {       // Example 1 - You tin flame purpose enhanced for loop alongside array     String[] currencies = { "JPY", "AUD", "USD" };       for (String currency : currencies) {       System.out.println(currency);     }       // Example 2 - You tin flame purpose enhanced for loop alongside collection     // e.g. list, ready or queue     Collection<Integer> primes = new HashSet<>();     primes.add(2);     primes.add(3);     primes.add(5);       for (Integer prime number : primes) {       System.out.println(prime);     }       // Example three - You tin flame purpose whatever object which implements Iterable     // alongside enhanced for loop inwards Java     MyIterable<Integer> custom = new Main.MyIterable<>(Arrays.asList(1, 2, 3));     for (Integer discover : custom) {       System.out.println(number);     }       // Example iv - You cannot withdraw elements when iterating over     // Collection using enhanced for loop, every bit iterator's remove()     // method is non accessible as well as Collection's remove() method     // volition throw ConcurrentModificationException     List<Integer> multiples = new ArrayList<>();     multiples.add(10);     multiples.add(20);     multiples.add(30);       for (Integer i : multiples) {       // multiples.remove(i);     }       // Example 5 - Iterating over a 2 dimensional array using     // enhanced for loop     int[][] cubes = { { 2, 4 }, { 3, 9 }, { 4, 16 } };       for (int[] numbers : cubes) {       for (int i : numbers) {         System.out.println(i);       }     }     }     private static class MyIterable<T> implements Iterable<T> {     private Collection<T> repository;       public MyIterable(Collection<T> source) {       repository = source;     }       @Override     public Iterator<T> iterator() {       return repository.iterator();     }     } }

That's all close how to iterate over Collection or array using enhanced for loop inwards Java. These examples clearly demonstrate mightiness as well as limitation of enhanced for loop inwards Java.  Try to purpose it on your day-to-day coding to improve the readability of your Java code.

Further Reading
The Complete Java MasterClass
tutorial)
  • Difference betwixt abstract aeroplane as well as interface inwards Java 8? (answer)
  • What is the default method inwards Java 8? (example)
  • How to format/parse the appointment alongside LocalDateTime inwards Java 8? (tutorial)
  • How to purpose peek() method inwards Java 8 (example)
  • How to purpose filter() method inwards Java 8 (tutorial)
  • 5 Books to Learn Java 8 from Scratch (books)
  • 20 Examples of Date as well as Time inwards Java 8 (tutorial)
  • How to form the map past times keys inwards Java 8? (example)
  • How to convert List to Map inwards Java 8 (solution)
  • How to form the may past times values inwards Java 8? (example)
  • How to bring together String inwards Java 8 (example)
  • 5 Free Courses to larn Java 8 as well as nine (courses)

  • Thanks for reading this article therefore far. If you lot similar this tutorial therefore delight part alongside your friends as well as colleagues. If you lot convey whatever question, dubiousness or feedback close this tutorial as well as my explanation therefore delight drib a note.

    P. S. - If you lot are looking for approximately gratuitous courses to larn recent changes on Java 8 as well as Java nine therefore you lot tin flame likewise run across this listing of Free Java 8 as well as nine Courses for Programmers

    No comments:

    Post a Comment