gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
loop for generic list java 8
- User
loop for generic list java 8
- Assistant
To loop through a generic list in Java 8 using the forEach method, you need to follow these steps:
- Create a generic list. For example:
List<String> myList = new ArrayList<String>(); myList.add("Hello"); myList.add("World");- Use the forEach method and a lambda expression to iterate through the list. The lambda expression is used to define the action to be performed on each element of the list.
myList.forEach(str -> System.out.println(str));This will print:
Hello WorldHere is a complete example:
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { // Creating a generic list List<String> myList = new ArrayList<String>(); // Adding some elements to the list myList.add("Hello"); myList.add("World"); // Looping through the list with forEach and lambda expression myList.forEach(str -> System.out.println(str)); } }