Code example for NavigableMap

Methods: getputremovefloorEntry

0
  } 
 
  @Override 
  public boolean add(Long aLong) {
    // Find the largest LongSegment with a min value of less than or equal to aLong 
    Map.Entry<Long, LongSegment> lowerEntry = map.floorEntry(aLong);
 
    // This value is already added 
    if (lowerEntry != null && lowerEntry.getValue().contains(aLong)) {
      return false; 
    } 
 
    // Get the LongSegment with a min value directly after aLong 
    LongSegment upperSegment = map.get(aLong + 1);
 
    // Determine possibly adjacencies with lower and upper bound LongSegments 
    boolean lowerAdjacent = lowerEntry != null && lowerEntry.getValue().getMax() + 1 == aLong;
    boolean upperAdjacent = upperSegment != null && upperSegment.getMin() - 1 == aLong;
 
    if (lowerAdjacent && upperAdjacent) {
 
      // Overwrite the lower adjacent to encompass the whole range 
      map.put(
        lowerEntry.getValue().getMin(),
        new LongSegment(lowerEntry.getValue().getMin(), upperSegment.getMax())
      ); 
 
      // Remove the upper adjacent b/c now included in the merged LongSegment 
      map.remove(upperSegment.getMin());
 
    } else if (lowerAdjacent) {
 
      // Overwrite the lower adjacent max to include aLong 
      map.put(
        lowerEntry.getValue().getMin(), new LongSegment(lowerEntry.getValue().getMin(), aLong)
      ); 
 
    } else if (upperAdjacent) {
 
      // Insert new LongSegment starting aLong and encompassing upper adjacent 
      map.put(aLong, new LongSegment(aLong, upperSegment.getMax()));
      // Remove the upper adjacent b/c now included in new LongSegment 
      map.remove(upperSegment.getMin());
 
    } else { 
 
      // No adjacents, so just insert singular element 
      map.put(aLong, new LongSegment(aLong));
 
    } 
 
    size++;
    return true;