Search code examples
javacollections

How to delete last element in java.util.Set?


I want to delete every last element of this set.

Set<String> listOfSources = new TreeSet<String>();
for(Route route:listOfRoutes){
    Set<Stop> stops = routeStopsService.getStops(route);
    for(Stop stop:stops)
       listOfSources.add(stop.getStopName());
}

Here I want to remove the last element from listOfSources.


Solution

  • You will need to cast back to TreeSet, as Set's don't have any order.

    listOfSources.remove( ((TreeSet) listOfSources).last() );