Question
How can I print a Java list by adding a new line after every 3rd element using a lambda expression?
List<String> items = Arrays.asList("A", "B", "C", "D", "E", "F", "G");
IntStream.range(0, items.size())
.forEach(i -> {
System.out.print(items.get(i) + " ");
if ((i + 1) % 3 == 0) {
System.out.println();
}
});
Answer
In Java, you can utilize lambda expressions and the Stream API to efficiently format the output of a list. This method allows you to insert a new line after every third element, enhancing the readability of the output.
List<String> items = Arrays.asList("A", "B", "C", "D", "E", "F", "G");
IntStream.range(0, items.size())
.forEach(i -> {
System.out.print(items.get(i) + " ");
if ((i + 1) % 3 == 0) {
System.out.println();
}
});
Causes
- You want to format output for better visual separation in console applications.
- Using lambda expressions can reduce boilerplate code.
Solutions
- Use IntStream to iterate over the indices of the list.
- Incorporate a conditional statement to print a new line after every third element.
Common Mistakes
Mistake: Forgetting to import the necessary packages (e.g., java.util.List and java.util.Arrays).
Solution: Ensure you have the correct imports at the top of your Java file.
Mistake: Not handling lists with fewer than three elements.
Solution: Consider boundary conditions and check list size before processing.
Helpers
- Java print list
- Java lambda expressions
- New line every third element
- Java Stream API