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
- 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);
- }
- }
- }
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
- 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());
- }
- }
- }
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