banner



How To Iterate Set In Java

In this tutorial, we will learn how to iterate Set in Java. Set interface does non provide any get() method like the List interface to think elements.

Therefore, the only way to take out elements from the set can be by using Iterator() method but this method does not return elements from set in whatever detail social club.

Let's see how many means to iterate prepare in Java.

At that place are mainly three ways to iterate a prepare in Java. We can iterate set past using any one of the following ways. They are equally follows:

  • Using Iterator
  • Using Enhanced for loop
  • Using forEach()

Ways to iterate set in java

How to iterate Fix using Iterator in Java?


Using Iterator method, we can traverse just in the forrad management from the first to last chemical element. We cannot traverse over elements in the backward direction using the iterator() method.

Let's take an example programme where nosotros will iterate elements of set using the iterator() method. Follow all the steps in the coding.

Plan source lawmaking 1:

packet iterateSet;  import java.util.HashSet;  import java.util.Iterator;  import coffee.util.Set;  public grade IterateSetEx  {  public static void principal(String[] args)  {  // Create a generic prepare object of type String.     Set<String> s = new HashSet<String>(); // s.size() is 0.    int size = s.size();    System.out.println("Size before adding elements: " +size);   // Adding elements to set.     due south.add("Orange"); // s.size() is 1.    s.add together("Red"); // due south.size() is 2.    s.add("Blue"); // s.size() is three.    s.add("Yellow"); // s.size() is iv.    s.add together("Green"); // s.size() is 5. System.out.println("Elements in set");  System.out.println(s);   Iterator<Cord> itr = s.iterator();  System.out.println("Iteration using Iterator method");  while(itr.hasNext()) {    Object str = itr.next();    System.out.println(str);   }   }  }
Output:         Size earlier adding elements: 0         Elements in set         [Cerise, Blue, Xanthous, Orange, Dark-green]         Iteration using Iterator method         Ruby-red Blue Yellow Orangish Green

During iteration, we cannot add together an element to a set at an iterator position. If we try to add an element during iteration, JVM will throw an exception named ConcurrentModificationException.

Cardinal indicate: Iteration means repeating the aforementioned operation multiple times.

Permit's have an example program where we will try to add an element during the iteration and run into which exception is thrown by JVM?

Program source code 2:

import java.util.HashSet; import java.util.Iterator; import java.util.Set;  public class AddDemo  { public static void main(String[] args)  {  Ready<String> fix= new HashSet<>();  fix.add("Banana");  set.add("Orange");  set up.add("Apple tree");  set up.add("Mango");    Iterator<String> itr = set.iterator();  while(itr.hasNext())   {     Object str = itr.next();     Organisation.out.println(str);     gear up.add("Grapes"); // Calculation element during iteration. It will throw ConcurrentModificationException.   }  } }
Output:        Apple        Exception in thread "principal" java.util.ConcurrentModificationException

However, we can remove a set element at an iterator position, just as nosotros practice with the list iterator.

Let's brand a program where we will remove a set element at an iterator position during iteration. Look at the following lawmaking to understand better.

Programme source lawmaking three:

import java.util.HashSet; import coffee.util.Iterator; import java.util.Set;  public course RemoveDemo  { public static void main(Cord[] args)  {  Set<String> prepare= new HashSet<>();  prepare.add("Banana");  set.add("Orange");  set.add("Apple");  set.add("Mango");    Iterator<String> itr = set.iterator();   while(itr.hasNext())   {     Object str = itr.next();     System.out.println(str);   // Removing Mango element.     if(str.equals("Mango"))    {       itr.remove();      }     }   System.out.println(gear up); } }
Output:       Apple       Mango       Orangish       Assistant       [Apple tree, Orange, Assistant]

Key signal: List can exist iterated past using the ListIterator method merely Set cannot be iterated by using ListIterator.

How to iterate Set using Enhanced For loop?


In this department, nosotros will iterate elements of set using enhanced for loop. Let'southward make a plan where we will iterate set elements using enhanced for loop.

Program source code 4:

package iterateSet;  import java.util.HashSet;  import java.util.Set;  public class IterateSetEx2  {  public static void main(String[] args)  {  // Create Prepare object of blazon Integer.     Set<Integer> southward = new HashSet<Integer>();  // Adding even numbers betwen x to thirty equally elements.     for(int i = 10; i < = thirty; i++)    {       if(i % ii == 0)       {         s.add(i);       }     }   System.out.println("Even numbers between ten to 30");   Arrangement.out.println(s);   System.out.println("Iteration Using Enchanced For Loop");   for(Integer it:s)  {     System.out.println(it);    }   }  }
Output:         Even numbers between 10 to 30         [xvi, xviii, xx, 22, 24, x, 26, 12, 28, xiv, 30]         Iteration Using Enhanced For Loop         16 xviii twenty 22 24 10 26 12 28 14 30

Iterate Set using forEach loop in Java 1.8?


This is the 3rd way to iterate ready elements using for forEach() method. It is a very simple way to iterate elements. Let's take an example plan based on this method.
Program source code v:

package iterateSet;  import java.util.HashSet;  import java.util.Prepare;  public class IterateSetEx3  {  public static void principal(String[] args)  {   Fix<Character> s = new HashSet<Character>();    s.add together('A');    southward.add('B');    southward.add('C');    s.add('D');    s.add together('E');   Organisation.out.println(southward);    System.out.println("Iterating using forEach loop in Java ane.8");   s.forEach(System.out::println);   }  }
Output:         [A, B, C, D, E]         Iterating using forEach loop in Java 1.viii         A B C D E

Fundamental indicate: forEach() method is bachelor from Java 1.viii onwards.


Hope that this tutorial has covered various types of case programs based on iterating set in Coffee. I hope that you lot volition accept understood this topic and enjoyed programming.
Thanks for reading!!!
Next ⇒ Java HashSet
⇐ PrevNext ⇒

How To Iterate Set In Java,

Source: https://www.scientecheasy.com/2020/10/iterate-set-in-java.html/

Posted by: crispnegards.blogspot.com

0 Response to "How To Iterate Set In Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel