How to delete last element in java.util.Set efficiently? List&lt;Route&gt; listOfRoutes = routeStopsService.getAllRoutes();
Set&lt;String&gt; listOfStopNames = new TreeSet&lt;String&gt;();
for(Route route:listOfRoutes){
    Set&lt;Stop&gt; stops = routeStopsService.getStops(route);
    for(Stop stop:stops)
        listOfStopNames .add(stop.getStopName());
    listOfStopNames .remove( ((TreeSet&lt;String&gt;) listOfSources).last());
}


Here I am getting list of stop names for every route, and I am removing the last stop name from every route.
First of all, you should always use block statements with the for loops. The original formatting of the question was this:

for(Stop stop:stops)
 listOfStopNames .add(stop.getStopName());
 listOfStopNames .remove( ((TreeSet&lt;String&gt;) listOfSources).last());


It's hard to read. Readers could think that the remove call is part of the for loop since it's the same indetation level as the line before.

for (final Stop stop : stops) {
    listOfStopNames.add(stop.getStopName());
}
listOfStopNames.remove(listOfSources.last());




Hungartion notation is redundant, try to avoid it. A few new names:


listOfRoutes -> routes
listOfStopNames -> stopNames
listOfSources -> sources




As @luketorjussen already mentioned, downcasting is nasty. If the implementation of listOfSources changes it may return another type and the compiler will not warn you but you'll get exceptions at runtime. At least change the casting to SortedSet instead of the TreeSet. TreeSet implements SortedSet and SortedSet has the required last method.



I'd extract out some method for better readability. For further review you should share some code from the routeStopsService, Router and Stop classes.

private Set&lt;String&gt; getStopNamesWithoutLast(final Route route) {
    final Set&lt;String&gt; result = getStopNames(route);
    final String lastStopName = ((SortedSet&lt;String&gt;) sources).last();
    result.remove(lastStopName);
    return result;
}

private Set&lt;String&gt; getStopNames(final Route route) {
    final Set&lt;String&gt; result = new TreeSet&lt;String&gt;();
    final Set&lt;Stop&gt; stops = routeStopsService.getStops(route);
    for (final Stop stop : stops) {
        final String stopName = stop.getStopName();
        result.add(stopName);
    }

    return result;
}




final List&lt;Route&gt; routes = routeStopsService.getAllRoutes();
final Set&lt;String&gt; allStopName = new TreeSet&lt;String&gt;();
for (final Route route : routes) {
    final Set&lt;String&gt; stopNames = getStopNamesWithoutLast(route);
    allStopName.addAll(stopNames);
}