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

I want to remove 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 item from listOfSources.

+5
source share
5 answers

You will need to return it back to the TreeSet, since Set has no order.

listOfSources.remove( ((TreeSet) listOfSources).last() );
+13
source

Alternatively, you can set listOfSources as SortedSet

SortedSet<String> listOfSources = new TreeSet<String>();

Then you can use the method last()without clicking on the TreeSet

listOfSources.remove(listOfSources.last());

I think this is the preferred approach since you believe your Set is in order.

+5
source
+2

- Stack. ( )

     Set<String> listOfSources = new TreeSet<String>();

     Stack<String> stack = new Stack<String>();
     stack.addAll(listOfSources);
     ...
     String lastElement = stack.pop();

pop() .

+1

NavigableSet pollLast .

NavigableSet Set.

, TreeSet :

  • . TreeSet TreeSet , , , , .
  • in fact, the fact that your logic requires you to remove the last element means that the behavior you expect from your variable is a behavior NavigableSet, not just that Set. So choosing this type of variable should make it explicit.
0
source

All Articles