LinkedHashset with looping

In this article, we will see how to loop LinkedHashset in java

Its very much common requirement to iterate or loop through LinkedHashset in java applications

There are mainly 2 ways to loop through LinkedHashset in java


1) Enhanced For loop
2) Iterator

Let’s see each of these ways with an example

1) Enhanced For loop

  1. import java.util.*;
  2.  
  3. public class LinkedHashSetEnhancedForLoop {
  4. public static void main(String[] args) {
  5. LinkedHashSet lhs= new LinkedHashSet();
  6. lhs.add(14);
  7. lhs.add(7);
  8. lhs.add(21);
  9. lhs.add(28);
  10. System.out.println(“Enhanced For Loop”);
  11. for (Integer element : lhs) {
  12. System.out.println(element);
  13. }
  14. }
  15. }
import java.util.*;

public class LinkedHashSetEnhancedForLoop {
public static void main(String[] args) {
LinkedHashSet lhs= new LinkedHashSet();
lhs.add(14);
lhs.add(7);
lhs.add(21);
lhs.add(28);
System.out.println(“Enhanced For Loop”);
for (Integer element : lhs) {
System.out.println(element);
}
}
}
Note : In the above example, we have used advanced/enhanced for loop to iterate LinkedHashSet


2) Iterator

  1. import java.util.*;
  2.  
  3. public class LinkedHashSetIterator {
  4. public static void main(String[] args) {
  5. LinkedHashSet lhs= new LinkedHashSet();
  6. lhs.add(14);
  7. lhs.add(7);
  8. lhs.add(21);
  9. lhs.add(28);
  10. System.out.println(While with iterator”);
  11. Iterator itr = lhs.iterator();
  12. while (itr.hasNext()) {
  13. System.out.println(itr.next());
  14. }
  15. }
  16. }
import java.util.*;

public class LinkedHashSetIterator {
public static void main(String[] args) {
LinkedHashSet lhs= new LinkedHashSet();
lhs.add(14);
lhs.add(7);
lhs.add(21);
lhs.add(28);
System.out.println(“While with iterator”);
Iterator itr = lhs.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Note : We can’t access LinkedHashSet elements using index in the way we access in Arraylist

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on