Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 last element from listOfSources.

like image 405
Ramesh Kotha Avatar asked Jan 07 '12 19:01

Ramesh Kotha


People also ask

How can the last element of a set be deleted?

The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. The last element of the Set can be deleted by by passing its iterator.

How do you remove the last element of a list in Java?

We can use the remove() method of ArrayList container in Java to remove the last element. ArrayList provides two overloaded remove() method: remove(int index) : Accept index of the object to be removed. We can pass the last elements index to the remove() method to delete the last element.

How do I remove an element from a set in Java?

remove(Object O) method is used to remove a particular element from a Set. Parameters: The parameter O is of the type of element maintained by this Set and specifies the element to be removed from the Set. Return Value: This method returns True if the specified element is present in the Set otherwise it returns False.


2 Answers

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

listOfSources.remove( ((TreeSet) listOfSources).last() );
like image 89
Dan Hardiker Avatar answered Oct 13 '22 20:10

Dan Hardiker


As an alternative you can set listOfSources as a SortedSet

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

Then you can use last() method without casting to TreeSet

listOfSources.remove(listOfSources.last());

I think that this is a preferred approach since you suppose that your Set has an order.

like image 22
Rogel Garcia Avatar answered Oct 13 '22 19:10

Rogel Garcia