USB
USB

Reputation: 6139

Iterating through SortedSet in Java

I am trying to create intervals for double values stored in a SortedSet.

Below is my code:

 public class Trail {
    public static void main(String[] args) {
        SortedSet<Double> val = new TreeSet<Double>();
        val.add(1.0);
        val.add(2.0);
        val.add(11.0);
        val.add(12.0);

        ArrayList<String> arr = new ArrayList<String>();
        double posinf = Double.POSITIVE_INFINITY;
        double neginf = Double.NEGATIVE_INFINITY;
        arr.add(neginf+ " - " +val.first());
        Iterator<Double> it = val.iterator();
        while (it.hasNext()) {
            // Get element
            Object lowerBound = it.next();
            Object upperBound = it.next();
            arr.add(lowerBound+" - "+upperBound);
        }
        arr.add(val.last() + " - "+ posinf);
        System.out.println("Range array: "+arr);
    }
 }

My current output is:

Range array: [-Infinity - 1.0, 1.0 - 2.0, 11.0 - 12.0, 12.0 - Infinity]

I expect range array as:

[-Infinity - 1.0, 1.0 - 2.0, 2.0 - 11.0, 11.0 - 12.0, 12.0 - Infinity]

Upvotes: 3

Views: 9395

Answers (3)

RajatPatel
RajatPatel

Reputation: 11

Problem is in following loop

while (it.hasNext()) {
    // Get element
    Object lowerBound = it.next();
    Object upperBound = it.next();
    arr.add(lowerBound+" - "+upperBound);
}

iterator it is being incremented twice it.next() in a single iteration that finally results in the array that you are getting.

Solution as below:

Double lowerBound = neginf;
while (it.hasNext()) {
    // Get element
    Double upperBound = it.next();
    arr.add(lowerBound + " - "+ upperBound);
    lowerBound = upperBound;
}

Upvotes: 0

gadeynebram
gadeynebram

Reputation: 725

Each it.next() call will forward the iterator with one step. Therefore in each iteration of your while loop you will loose one interval. Use a temporary variable to keep the previous iterator value.

For something like

Iterator<Double> it = val.iterator();
Object end=null;
if(it.hasNext()){
    end= it.next();
    //write out -infinity to previous.
}
while(it.hasNext()){
    Object start = end;
    end= it.next();
    //write out start - end interval
}
if(end != null){
// write out end to infinity 
} else {
   // there were no values in the array.
   // write out - infinity to infinity?
}

Upvotes: 0

Eran
Eran

Reputation: 393916

You are consuming two elements in each iteration of your loop (which would have thrown an exception if the number of elements was odd). You should consume just one in each iteration :

    Iterator<Double> it = val.iterator();
    Double lowerBound = neginf;
    while (it.hasNext()) {
        // Get element
        Double upperBound = it.next();
        arr.add(lowerBound+" - "+upperBound);
        lowerBound = upperBound;
    }
    arr.add(lowerBound  + " - "+ posinf);

Upvotes: 7

Related Questions