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<String>) 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<String> getStopNamesWithoutLast(final Route route) {
final Set<String> result = getStopNames(route);
final String lastStopName = ((SortedSet<String>) sources).last();
result.remove(lastStopName);
return result;
}
private Set<String> getStopNames(final Route route) {
final Set<String> result = new TreeSet<String>();
final Set<Stop> stops = routeStopsService.getStops(route);
for (final Stop stop : stops) {
final String stopName = stop.getStopName();
result.add(stopName);
}
return result;
}
final List<Route> routes = routeStopsService.getAllRoutes();
final Set<String> allStopName = new TreeSet<String>();
for (final Route route : routes) {
final Set<String> stopNames = getStopNamesWithoutLast(route);
allStopName.addAll(stopNames);
}