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 ?
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 -> ...);
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With