Issue
How can I remove a specific string in a list of objects by inputting the string? I tried to remove the index itself using flightList.remove(indexnum) which worked, but I want to remove a specific string such as only flight name.
//inputting string to be added in list
case 1:
System.out.println("Enter flight name: ");
//first sc.nextLine() is to flush the enter button
sc.nextLine();
flightName= sc.nextLine();
System.out.println("Enter flight number: ");
flightNumber= sc.nextLine();
Flight flight1 = new Flight(flightName, flightNumber);
//adding object to list
flightList.add(flight1);
break;
//remove specific string
case 2:
System.out.println("Enter flight name or flight number to be removed");
sc.nextLine();
String removeDetail = sc.nextLine();
flightList.remove(removeDetail);
break;
Solution
There are a few methods that can be used to remove elements from lists. You've already found remove(int)
. There's of course remove(E)
, but that requires a Flight
object. Fortunately, since Java 8 there's also removeIf(Predicate)
:
flightList.removeIf(f -> f.getFlightName().equals(removeDetail));
There's one small drawback, and that is that it will try to delete all elements that match, and therefore has to traverse the entire list. If you don't want that, use an iterator instead:
for (Iterator<Flight> iterator = flightList.iterator(); iterator.hasNext(); /* explicitly empty */ ) {
Flight flight = iterator.next();
if (flight.getFlightName().equals(removeDetail)) {
iterator.remove();
break; // this is the main difference with removeIf
}
}
Answered By - Rob Spoor
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.