private Optional<NearestKeyValue> getNearest(
      final SegmentIdentifier segmentIdentifier,
      final Predicate<Map.Entry<Bytes, Optional<byte[]>>> samePrefixPredicate,
      final Predicate<Map.Entry<Bytes, Optional<byte[]>>> fallbackPredicate,
      final boolean useMin)
      throws StorageException {

    final Lock lock = rwLock.readLock();
    lock.lock();
    try {
      final Map<Bytes, Optional<byte[]>> segmentMap =
          this.hashValueStore.computeIfAbsent(segmentIdentifier, s -> newSegmentMap());

      final Function<Predicate<Map.Entry<Bytes, Optional<byte[]>>>, Optional<NearestKeyValue>>
          findNearest =
              (predicate) -> {
                final Stream<Map.Entry<Bytes, Optional<byte[]>>> filteredStream =
                    segmentMap.entrySet().stream().filter(predicate);
                // Depending on the useMin flag, find either the minimum or maximum entry according
                // to key order
                final Optional<Map.Entry<Bytes, Optional<byte[]>>> sortedStream =
                    useMin
                        ? filteredStream.min(
                            (t1, t2) -> compareKeyLeftToRight(t1.getKey(), t2.getKey()))
                        : filteredStream.max(
                            (t1, t2) -> compareKeyLeftToRight(t1.getKey(), t2.getKey()));
                return sortedStream.map(
                    entry -> new NearestKeyValue(entry.getKey(), entry.getValue()));
              };

      // First, attempt to find a key-value pair that matches the same prefix
      final Optional<NearestKeyValue> withSamePrefix = findNearest.apply(samePrefixPredicate);
      if (withSamePrefix.isPresent()) {
        return withSamePrefix;
      }
      // If a matching entry with a common prefix is not found, the next step is to search for the
      // nearest key that comes after or before the requested one.
      return findNearest.apply(fallbackPredicate);
    } finally {
      lock.unlock();
    }
  }
Instantiates a new In memory key value storage with specific set of segments.

@param segments the segments to be used
services/kvstore/src/main/java/org/hyperledger/besu/services/kvstore/SegmentedInMemoryKeyValueStorage.java