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.
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.
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.
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.
You will need to cast back to TreeSet, as Set's don't have any order.
listOfSources.remove( ((TreeSet) listOfSources).last() );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With