Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing next element in Treeset in Java

Is there any way to access the successor or the predecessor of an element in Treeset of Java. Or is there any way of getting the iterator of a particular element so that we can use iterator.next() to get the next element.

like image 446
kaushalpranav Avatar asked Mar 19 '16 09:03

kaushalpranav


People also ask

Does TreeSet follow insertion order?

HashSet does not maintain any order while LinkedHashSet maintains insertion order of elements much like List interface and TreeSet maintains sorting order or elements.

Does TreeSet have order?

Objects in a TreeSet are stored in a sorted and ascending order. TreeSet does not preserve the insertion order of elements but elements are sorted by keys.

How do you get the last element in TreeSet?

last() method is used to return the last of the element of a TreeSet. The last element here is being referred to the highest of the elements in the set. If the elements are of integer types, then the largest integer is returned.


2 Answers

use higher/lower

with the TreeSet set

is set.higher(e) like e.next() and set.lower(e) like e.prev()

like image 154
Turo Avatar answered Sep 23 '22 09:09

Turo


You can get a particular TreeSet's iterator using the iterator() method, and you can retrieve a reverse iterator with the use of descendingIterator() method.

like image 29
masm64 Avatar answered Sep 23 '22 09:09

masm64