Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through SortedSet in Java

Tags:

java

sortedset

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]
like image 805
Unmesha Sreeveni U.B Avatar asked May 29 '26 19:05

Unmesha Sreeveni U.B


1 Answers

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);
like image 149
Eran Avatar answered Jun 01 '26 08:06

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!