Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peek at next element in a Tree set using an iterator

I was wondering if there was a way to accomplish this, or if there are alternative data structures. It has to be sorted, without duplicates, and have an iterator.

like image 764
Bobby Avatar asked Dec 13 '22 04:12

Bobby


1 Answers

TreeSet has an iterator, is sorted, won't have duplicates, and is able to see the next higher element by using higher.

For example:

TreeSet<Integer> ts = new TreeSet<Integer>();
ts.add(1);
ts.add(4);
ts.add(4);
ts.add(3);

for (Integer i : ts) {
  System.out.println("current: " + i + " next:  " + ts.higher(i));
}

The output is:

current: 1  next: 3
current: 3  next: 4
current: 4  next: null
like image 61
coobird Avatar answered Jan 20 '23 23:01

coobird