I have this method that searches a list of arrays of type Person and deletes a specific one based on the first name.
It works fine.
But it only deletes one person and then stops.
public void deleteFriend(String firstName){
Person friendToDelete = null;
for(Person f : friendsList){
if(f.getFirstName().equalsIgnoreCase(firstName)){
friendToDelete = f;
}
}
if(friendToDelete != null){
friendsList.remove(friendToDelete);
System.out.println("Friend deleted.");
}
}
Say my list friendsList has two people with the first name Shane. I want my method to delete all Shanes.
I have tried the following:
public void deleteFriend(String firstName){
//Person friendToDelete = null;
for(Person f : friendsList){
if(f.getFirstName().equalsIgnoreCase(firstName)){
friendsList.remove(f);
continue;
}
}
}
In the above example, I tried some variations of the if loop. First, I tried break; instead of continue;. I also tried removing that line altogether.
if(f.getFirstName().equalsIgnoreCase(firstName))
friendsList.remove(f);
It still only deleted the first Shane.
I tried to make a condition to check if there are instances of Person with the first name Shane and while that is true, go through the list with for(Person f : friendsList) and remove it. And then check if there still is a Shane, and do it again.
But I can tell that what I have isn’t going to work:
public void deleteFriend(String firstName){
//Person friendToDelete = null;
for(Person f : friendsList){
int cond = 0;
while(cond == 0){
if(f.getFirstName().equalsIgnoreCase(firstName)){
friendsList.remove(f);
}
else{
// ??? cond = 1?
}
}
}
}
Can someone help me with what I’m trying to do or point me in the right direction?
>Solution :
You can use Java Streams to do so and make your code waaaaay simpler. To perform a delete operation in a list based in a condition just do:
friendsList.removeIf(p -> p.getFirstName().equalsIgnoreCase(firstName));
Here is a bit of more on it: https://www.baeldung.com/java-use-remove-item-stream