Intro
When I was going through and learning Java. I wished there was a collection of docs that was written that explains Java topics simply.
Iterating through arrays
This is the standard for-loop. This is in a lot of different languages as well
int[] myArray = {1, 2, 3, 4, 5};
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]); // logic to log element
}
A more concise way to iterate through an array, especially beneficial when you don't need the index.
int[] myArray = {1, 2, 3, 4, 5};
for (int element : myArray) {
System.out.println(element);
}
The Streams API introduced in Java 8 offers a functional approach to array iteration.
int[] myArray = {1, 2, 3, 4, 5};
Arrays.stream(myArray).forEach(System.out::println);
Ideal for iterating backward through a List, providing more control over traversal.
List<Integer> myList = Arrays.asList(1, 2, 3, 4, 5);
ListIterator<Integer> iterator = myList.listIterator(myList.size());
while (iterator.hasPrevious()) {
System.out.println(iterator.previous());
}
Iterating through objects
For iterating through key-value pairs in a Map, Map.Entry allows access to both the key and the value.
Map<String, Integer> myMap = new HashMap<>();
myMap.put("a", 1);
myMap.put("b", 2);
myMap.put("c", 3);
for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Leveraging the powerful Streams API for concise and functional iteration through Map entries.
Map<String, Integer> myMap = new HashMap<>();
myMap.put("a", 1);
myMap.put("b", 2);
myMap.put("c", 3);
myMap.entrySet().stream().forEach(entry -> {
System.out.println(entry.getKey() + ": " + entry.getValue());
});
Things to look out for
Understanding the distinction between immutable and mutable lists is crucial. An immutable list cannot be modified after creation, while a mutable list allows changes. Consider your use case and requirements when choosing between them.
Thank you for reading! I hope this information proves helpful.
Top comments (0)