Search code examples
javalambdaforeach

Java List forEach Lambda expressional - first elements and loop through all elements


I can able to loop through all elements of List like below:

userList.forEach(user -> {
    System.out.println(user);
});

I want to print the user object only for first element but I should loop for all elements in list. How to achieve that ?


Solution

  • If you want to apply certain logic to first user and continue looping with others then you might use condition to check the first object is the current or not. As I understand from your question, this is what you want

    userList.forEach(user -> {
        if (userList.get(0) == user)
            System.out.println("This is user with index 0");
        System.out.println(user + " All users including 0");
    });
    

    As Aomine said in the comments, this might not be great solution for checking the first element of the list each time and might not work correctly if the same user object is repeated on the list so better to separate the logic like this

    // Do something with the first user only
    if(!userList.isEmpty())
        System.out.println(userList.get(0));
    
    // Do some stuff for all users in the list except the first one
    userList.subList(1, userList.size()).forEach(user -> {
            System.out.println(user + " All users without 0");
    );
    
    // Do some stuff for all users in the list
    userList.forEach(user -> {
            System.out.println(user + " All users");
    );
    

    Another approach using stream

    // Dealing with first user only
    if (!userList.isEmpty()) {
        System.out.println("this is first user: " + userList.get(0));
    }
    // using stream skipping the first element
    userList.stream().skip(1).forEach(user -> {
        System.out.println(user);
    });
    

    Also you might use iterator approach

    // getting the iterator from the list
    Iterator<String> users = userList.iterator();
    
    // the first user
    if(users.hasNext())
        System.out.println("this is first user :" + users.next());
    
    // the rest of the users
    users.forEachRemaining(user -> {
        System.out.println(user);
    });