Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java List forEach Lamba 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 ?

like image 381
Krish Avatar asked Oct 17 '22 15:10

Krish


2 Answers

It seems like you're asking, how to print the first object but iterate over the remaining elements and do some other logic with them, in which case you can go with:

if(!userList.isEmpty()) System.out.println(userList.get(0));
userList.subList(1, userList.size()).forEach(user -> ...);
like image 87
Ousmane D. Avatar answered Oct 21 '22 07:10

Ousmane D.


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);
});
like image 24
Anddo Avatar answered Oct 21 '22 07:10

Anddo