Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

loop for generic list java 8

  1. User

    loop for generic list java 8

  2. Assistant

    To loop through a generic list in Java 8 using the forEach method, you need to follow these steps:

    1. Create a generic list. For example:
    List<String> myList = new ArrayList<String>();
    myList.add("Hello");
    myList.add("World");
    
    1. 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
    World
    

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