How can Iterator can using in set?

Like you are using it.

How can get the values โ€‹โ€‹one by one through an iterator?

Your code is doing that.

Is iterator changing set into like list which ordered data structure?

No.

The thing that you are missing is what "unordered" means. It means that the order in which the (set's) elements are returned is not predictable1, and not specified in the javadocs. However each element will be returned once and (since the elements of a set are unique!) only once for the iteration.


1 - Actually, this is not strictly true. If you have enough information about the element class, the element values, how they were created and how / when they were added to the HashSet, AND you analyze the specific HashSet implementation ... it is possible that you CAN predict what the iteration order is going to be. For example if you create a HashSet<Integer> and add 1, 2, 3, 4, ... to it, you will see a clear (and repeatable) pattern when you iterate the elements. This is in part due to the way that Integer.hashCode() is specified.

Answer from Stephen C on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ set-iterator-method-in-java-with-examples
Set iterator() method in Java with Examples - GeeksforGeeks
December 31, 2018 - The java.util.Set.iterator() method is used to return an iterator of the same elements as the set. The elements are returned in random order from what present in the set. Syntax: Iterator iterate_value = Set.iterator(); Parameters: The function ...
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java collections โ€บ iterate over a set in java
Iterate Over a Set in Java | Baeldung
June 27, 2025 - That means that we canโ€™t ask about a specific element of the set by its number. Because of that, we canโ€™t use a typical for loop or any other index-based method. The most basic and close-to-metal method of iterating over the set is invoking the iterator method exposed by every Set:
Discussions

How can Iterator can using in set(java)? - Stack Overflow
Is iterator changing set into like list which ordered data structure? ... The thing that you are missing is what "unordered" means. It means that the order in which the (set's) elements are returned is not predictable1, and not specified in the javadocs. More on stackoverflow.com
๐ŸŒ stackoverflow.com
How do I iterate and modify Java Sets? - Stack Overflow
Let's say I have a Set of Integers, and I want to increment every Integer in the Set. How would I do this? Am I allowed to add and remove elements from the set while iterating it? Would I need to More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - How to Iterate over a Set/HashSet without an Iterator? - Stack Overflow
Iterators are only temporarily ... ArrayList.java source for example). If used in a game loop for iterating scene objects and considering at least 30 updates per second you end up with at least 60 (scene is usually iterated twice per cycle) iterator objects per second in memory waiting for GC. That has a big impact on Android. ... Perhaps one should pick a more adequate data structure in that case? A set's not designed ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to use Iterator on a set

You get a NoSuchElementException because you call next on an iterator that has no next element. Call hasNext first, to ensure that the iterator is not empty, before calling next.

Your first code snippet does not compile because you call getPositionX twice, once on your double test.

More on reddit.com
๐ŸŒ r/javahelp
5
2
February 24, 2019
๐ŸŒ
Codecademy
codecademy.com โ€บ docs โ€บ java โ€บ iterator โ€บ .set()
Java | Iterator | .set() | Codecademy
June 30, 2022 - The .set() method replaces the current entry in the underlying collection of a ListIterator object. This is the last item returned by the .next() or .previous() methods. ... Looking for an introduction to the theory behind programming?
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ examples โ€บ iterate-over-set
Java Program to Iterate over a Set
Here, we have used the for-each loop to iterate each element of the set. import java.util.Set; import java.util.HashSet; import java.util.Iterator; class Main { public static void main(String[] args) { // Creating an Set Set<Integer> numbers = new HashSet<>(); numbers.add(1); numbers.add(3); numbers.add(2); System.out.println("Set: " + numbers); // Creating an instance of Iterator Iterator<Integer> iterate = numbers.iterator(); System.out.println("Iterating over Set:"); while(iterate.hasNext()) { System.out.print(iterate.next() + ", "); } } }
๐ŸŒ
Study.com
study.com โ€บ business courses โ€บ business 104: information systems and computer applications
How to Iterate Set in Java - Lesson | Study.com
November 25, 2024 - In order to use it, you need to create a new instance of the Iterator. Next, we make use of a 'while' loop that runs while the set has a next item to look for. The Iterator interface provides us with a method, hasNext(), which returns false ...
๐ŸŒ
Scientech Easy
scientecheasy.com โ€บ home โ€บ blog โ€บ how to iterate set in java
How to Iterate Set in Java - Scientech Easy
May 12, 2025 - Using Iterator method, we can traverse the set only in the forward direction from the first to last element and access its elements one by one. We cannot traverse over set elements in the backward direction using the iterator() method. [blocksy-content-block id=โ€12371โ€ณ] Example 1: Letโ€™s write a simple Java program in which we will iterate elements of set using the iterator() method.
Top answer
1 of 4
3

How can Iterator can using in set?

Like you are using it.

How can get the values โ€‹โ€‹one by one through an iterator?

Your code is doing that.

Is iterator changing set into like list which ordered data structure?

No.

The thing that you are missing is what "unordered" means. It means that the order in which the (set's) elements are returned is not predictable1, and not specified in the javadocs. However each element will be returned once and (since the elements of a set are unique!) only once for the iteration.


1 - Actually, this is not strictly true. If you have enough information about the element class, the element values, how they were created and how / when they were added to the HashSet, AND you analyze the specific HashSet implementation ... it is possible that you CAN predict what the iteration order is going to be. For example if you create a HashSet<Integer> and add 1, 2, 3, 4, ... to it, you will see a clear (and repeatable) pattern when you iterate the elements. This is in part due to the way that Integer.hashCode() is specified.

2 of 4
1

Referring to the documentation, we see that:

Iterator<E> iterator()

Returns an iterator over the elements in this collection. There are no guarantees concerning the order in which the elements are returned (unless this collection is an instance of some class that provides a guarantee).


Since there are no guarantees concerning the order in which the elements are returned for iterator, it is not a problem for iterator to apply to Set, which is unordered.

Further, it is not changing the Set into a List

Find elsewhere
๐ŸŒ
JavaBeat
javabeat.net โ€บ home โ€บ how to use set iterator() method in java
How to Use Set iterator() Method in Java
April 2, 2024 - The only way to extract elements ... each loop). More specifically, you can invoke the iterator() method of the Set interface to get the iterator and then traverse it using a loop....
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ java_iterator.asp
Java Iterator
To use an Iterator, you must import it from the java.util package.
๐ŸŒ
Techie Delight
techiedelight.com โ€บ home โ€บ java โ€บ iterate over a set in java
Iterate over a Set in Java | Techie Delight
July 7, 2026 - This post will discuss various methods to iterate over set in Java.. We can use `iterator()` that returns an iterator to iterate over a set..
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2016 โ€บ 01 โ€บ 3-ways-to-loop-over-set-or-hashset-in-java.html
3 ways to loop over Set or HashSet in Java? Examples
Since Set interface or HashSet ... or loop over Set using advanced for loop of Java 5. You can get the iterator by calling the iterator() method of the Set interface....
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ java โ€บ examples โ€บ iterate-over-a-set
Java Program to Iterate over a Set | Vultr Docs
December 6, 2024 - By using an Iterator, you gain more control over the iteration process, such as the ability to remove elements during iteration which is not possible directly with a for-each loop. Initialize your Set. Use Java 8 Stream API to iterate through the Set.
๐ŸŒ
Jenkov
jenkov.com โ€บ tutorials โ€บ java-collections โ€บ iterator.html
Java Iterator
May 22, 2020 - The order in which the elements contained in a Java Iterator are traversed depends on the object that supplies the Iterator. For instance, an iterator obtained from a List will iterate through the elements of that List in the same order the elements are stored internally in the List. An Iterator obtained from a Set, on the other hand, does not make any guarantees about the exact sequence the elements in the Set are iterated in.
Top answer
1 of 5
96

You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().

however, Integer objects are immutable; my strategy would be to iterate through the set and for each Integer i, add i+1 to some new temporary set. When you are finished iterating, remove all the elements from the original set and add all the elements of the new temporary set.

Set<Integer> s; //contains your Integers
...
Set<Integer> temp = new Set<Integer>();
for(Integer i : s)
    temp.add(i+1);
s.clear();
s.addAll(temp);
2 of 5
42

You can do what you want if you use an iterator object to go over the elements in your set. You can remove them on the go an it's ok. However removing them while in a for loop (either "standard", of the for each kind) will get you in trouble:

Set<Integer> set = new TreeSet<Integer>();
    set.add(1);
    set.add(2);
    set.add(3);

    //good way:
    Iterator<Integer> iterator = set.iterator();
    while(iterator.hasNext()) {
        Integer setElement = iterator.next();
        if(setElement==2) {
            iterator.remove();
        }
    }

    //bad way:
    for(Integer setElement:set) {
        if(setElement==2) {
            //might work or might throw exception, Java calls it indefined behaviour:
            set.remove(setElement);
        } 
    }

As per @mrgloom's comment, here are more details as to why the "bad" way described above is, well... bad :

Without getting into too much details about how Java implements this, at a high level, we can say that the "bad" way is bad because it is clearly stipulated as such in the Java docs:

https://docs.oracle.com/javase/8/docs/api/java/util/ConcurrentModificationException.html

stipulate, amongst others, that (emphasis mine):

"For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected" (...)

"Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception."

To go more into details: an object that can be used in a forEach loop needs to implement the "java.lang.Iterable" interface (javadoc here). This produces an Iterator (via the "Iterator" method found in this interface), which is instantiated on demand, and will contain internally a reference to the Iterable object from which it was created. However, when an Iterable object is used in a forEach loop, the instance of this iterator is hidden to the user (you cannot access it yourself in any way).

This, coupled with the fact that an Iterator is pretty stateful, i.e. in order to do its magic and have coherent responses for its "next" and "hasNext" methods it needs that the backing object is not changed by something else than the iterator itself while it's iterating, makes it so that it will throw an exception as soon as it detects that something changed in the backing object while it is iterating over it.

Java calls this "fail-fast" iteration: i.e. there are some actions, usually those that modify an Iterable instance (while an Iterator is iterating over it). The "fail" part of the "fail-fast" notion refers to the ability of an Iterator to detect when such "fail" actions happen. The "fast" part of the "fail-fast" (and, which in my opinion should be called "best-effort-fast"), will terminate the iteration via ConcurrentModificationException as soon as it can detect that a "fail" action has happen.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ hashset-iterator-method-in-java
Java HashSet iterator() Method - GeeksforGeeks
July 11, 2025 - // Java program to demonstrates the use of HashSet to store // of HashSet to store custom objects and the traversal // of these objects using an iterator import java.util.HashSet; import java.util.Iterator; public class Geeks { public static void main(String args[]) { // create hash set HashSet<Employee> hs = new HashSet<>(); hs.add(new Employee(10, "Geek1")); hs.add(new Employee(2, "Geek20")); hs.add(new Employee(35, "Geek5")); // create an iterator Iterator<Employee> i = hs.iterator(); // iterate through the HashSet and // print each employee object while (i.hasNext()) { System.out.println("
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ how to use iterator on a set
r/javahelp on Reddit: How to use Iterator on a set
February 24, 2019 -

I was trying to get a method of a object in a LinkedHashSet, but I get errors. Can Someone please explain why this doesn't work?

This doesn't work

Iterator<className> it = model.getLinkedHashSet().iterator();
while(it.hasNext()) {
double test = it.next().getPositionX();
rectangle = new Rectangle(test,0,100 , 100);}

This works

Iterator<className> it = model.getLinkedHashSet().iterator();
while(it.hasNext()) {
className element = it.next();
test = element.getPositionX();
rectangle = new Rectangle(test,0,100 , 100);}

The error I get is:

Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389) at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767) Caused by: java.lang.RuntimeException: Exception in Application start method at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917) at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182) at java.lang.Thread.run(Thread.java:748) Caused by: java.util.NoSuchElementException at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:721) at java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:742) at view.blabla.BlaBlaPresenter.updateView(BlaBlaPresenter.java:122) at view.blabla.BlaBlaPresenter.<init>(BlaBlaPresenter.java:27) at Main.start(Main.java:26) at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863) at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326) at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294) at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177) ... 1 more Exception running application Main

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ java-program-to-iterate-over-a-set
Java - Set Interface
June 17, 2025 - Following is an example to explain Set functionality using HashSet โˆ’ ยท import java.util.HashSet; import java.util.Set; public class SetDemo { public static void main(String args[]) { int count[] = {34, 22,10,60,30,22}; Set<Integer> set = new HashSet<>(); try { for(int i = 0; i < 5; i++) { set.add(count[i]); } System.out.println(set); } catch(Exception e) {} } }
๐ŸŒ
BeginnersBook
beginnersbook.com โ€บ 2014 โ€บ 08 โ€บ how-to-iterate-over-a-sethashset
Java โ€“ How to Iterate over a Set/HashSet
import java.util.HashSet; import java.util.Iterator; class IterateHashSet{ public static void main(String[] args) { // Create a HashSet HashSet<String> hset = new HashSet<String>(); //add elements to HashSet hset.add("Chaitanya"); hset.add("Rahul"); hset.add("Tim"); hset.add("Rick"); hset.add("Harry"); Iterator<String> it = hset.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } } Output: Chaitanya Rick Harry Rahul Tim ยท import java.util.HashSet; import java.util.Set; class IterateHashSet{ public static void main(String[] args) { // Create a HashSet Set<String> hset = new HashSet<String>(); //add elements to HashSet hset.add("Chaitanya"); hset.add("Rahul"); hset.add("Tim"); hset.add("Rick"); hset.add("Harry"); for (String temp : hset) { System.out.println(temp); } } } Output: Chaitanya Rick Harry Rahul Tim ยท