Java TreeSet get smaller value element

Description

Java TreeSet get smaller value element

import java.util.TreeSet;

class MyValue implements Comparable<MyValue> {
  long value;//from www .  ja v a 2  s . c o  m
  int id;

  public MyValue(int id, long v) {
    this.id = id;
    this.value = v;
  }

  public MyValue(long v) {
    this.id = -1;
    this.value = v;
  }

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

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

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



PreviousNext

Related