All Downloads are FREE. Search and download functionalities are using the official Maven repository.

no.mnemonic.commons.utilities.lambda.TryStreamImpl Maven / Gradle / Ivy

package no.mnemonic.commons.utilities.lambda;

import java.util.stream.Collector;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;

class TryStreamImpl implements TryStream {
  private final Stream stream;

  TryStreamImpl(Stream stream) {
    this.stream = stream;
  }

  @Override
  public  TryStream map(ExceptionalFunction mapper) {
    return new TryStreamImpl<>(stream.map(v -> applyExceptionalFunction(mapper, v)));
  }

  @Override
  public Stream stream() {
    return stream;
  }

  @Override
  public LongStream mapToLong(ExceptionalFunction function) throws E {
    return stream.mapToLong(v -> applyExceptionalFunction(function, v));
  }

  @Override
  public IntStream mapToInt(ExceptionalFunction function) throws E {
    return stream.mapToInt(v -> applyExceptionalFunction(function, v));
  }

  @Override
  public TryStream filter(ExceptionalPredicate predicate) {
    return new TryStreamImpl<>(stream.filter(o -> {
      try {
        return predicate.test(o);
      } catch (Exception e) {
        if (e instanceof RuntimeException) throw (RuntimeException) e;
        throw new StreamException(e);
      }
    }));
  }

  @Override
  public  R collect(Collector collector) throws E {
    try {
      return stream.collect(collector);
    } catch (StreamException e) {
      //noinspection unchecked
      throw (E) e.getCause();
    }
  }

  @Override
  public void forEach(ExceptionalConsumer consumer) throws E {
    try {
      stream.forEach(el -> {
        try {
          consumer.accept(el);
        } catch (Exception e) {
          if (e instanceof RuntimeException) throw (RuntimeException) e;
          throw new StreamException(e);
        }
      });
    } catch (StreamException e) {
      //noinspection unchecked
      throw (E) e.getCause();
    }
  }


  private  R applyExceptionalFunction(ExceptionalFunction mapper, T v) {
    try {
      return mapper.apply(v);
    } catch (Exception e) {
      if (e instanceof RuntimeException) throw (RuntimeException) e;
      throw new StreamException(e);
    }
  }

  private static class StreamException extends RuntimeException {
    StreamException(Throwable cause) {
      super(cause);
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy