We can traverse the List, Queue, Set, and Map interface in various approaches. Like - Loop, Iterator, Lamda Expressions, and Java Streams. Below are the different traverse methods for such interfaces.
Traverse Approaches are -
- For Loop
- Enhanced For Loop
- Iterator
- Stream API
- Lamda Expression (forEach)
List, Queue, and Set use the same syntax. Therefore, just ArrayList is shown below.
List<String> list = new ArrayList<>();list.add("A");list.add("B");list.add("C");
1. For Loop
for (int i = 0; i < list.size(); i++) {System.out.println(list.get(i));}
2. Enhanced For Loop
for (String item : list) {System.out.println(item);}
3. Iterator
Iterator<String> iterator = list.iterator();while (iterator.hasNext()) {System.out.println(iterator.next());}
4. Stream API
list.stream().forEach(System.out::println);
5. Stream using Lamda Expression
list.stream().forEach(item -> {String result = item.toLowerCase();System.out.println("Processed: " + result);});
Executed code
Map Interface:
Map<String, Integer> map = new HashMap<>();map.put("A", 1);map.put("B", 2);map.put("C", 3);
1. Enhance for loop (entry set)
for (Map.Entry<String, Integer> entry : map.entrySet()) {System.out.println(entry.getKey() + " = " + entry.getValue());}
2. Enhance for loop (key set)
for (String key : map.keySet()) {System.out.println(key + " = " + map.get(key));}
3. Enhance for loop (values)
for (Integer value : map.values()) {System.out.println(value);}
4. Iterator
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();while (iterator.hasNext()) {Map.Entry<String, Integer> entry = iterator.next();System.out.println(entry.getKey() + " = " + entry.getValue());}
5. Stream API
map.entrySet().stream().forEach(entry ->System.out.println(entry.getKey() + " = " + entry.getValue()));
6. Using Lamda Expression
map.forEach((key, value) -> System.out.println(key + " = " + value));
Executed code
0 Comments