Java Collection How to - Find Range in which value lies








Question

We would like to know how to find Range in which value lies.

Answer

/*from   w ww .j a  v  a  2 s.  c  o m*/
import java.util.TreeSet;

class MyRange implements Comparable<MyRange> {
  long limit;
  int id;

  public MyRange(int id, long credits) {
    this.id = id;
    this.limit = credits;
  }

  public MyRange(long credits) {
    this.id = -1;
    this.limit = credits;
  }

  @Override
  public int compareTo(MyRange o) {
    return limit < o.limit ? -1 : limit > o.limit ? 1 : 0;
  }

  @Override
  public String toString() {
    return "id:" + id + ", limit:" + limit;
  }
}

public class Main {
  public static void main(String[] args) {
    TreeSet<MyRange> set = new TreeSet<>();
    set.add(new MyRange(1, 0));
    set.add(new MyRange(2, 100));
    set.add(new MyRange(3, 500));
    set.add(new MyRange(4, 250));
    System.out.println(set.floor(new MyRange(50)));
    System.out.println(set.floor(new MyRange(300)));
    System.out.println(set.floor(new MyRange(600)));
  }
}

The code above generates the following result.