Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
stream handlingException
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.stream.*; import java.util.*; import java.lang.*; import java.lang.reflect.*; import java.io.*; import java.util.function.*; class Rextester { public static void main(String args[]) throws IOException { IntStream.rangeClosed(1, 10).boxed() .collect(handlingException(IOException.class, num -> throwOnOddNumber(num))) .rethrow(); } private static void throwOnOddNumber(int num) throws IOException { if (num % 2 != 0) { throw new IOException("this number is odd: " + num); } } static <T, E extends Throwable> Collector<T, List<E>, OptionalThrowable<E>> handlingException(Class<E> exceptionClass, ThrowingFunction<T, E> fn) { BiConsumer<List<E>, T> accumulator = (list, arg) -> { try { fn.accept(arg); } catch (Throwable e) { if (exceptionClass.isInstance(e)) { list.add(exceptionClass.cast(e)); } else if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new RuntimeException("Unexpected checked exception", e); } } }; Function<List<E>, OptionalThrowable<E>> finisher = list -> { Optional<E> e = list.stream().reduce((e1, e2) -> { e1.addSuppressed(e2); return e1; }); return new OptionalThrowable<E>(e); }; BinaryOperator<List<E>> combiner = (l1, l2) -> { l1.addAll(l2); return l1; }; return Collector.of(ArrayList::new, accumulator, combiner, finisher); } static interface ThrowingFunction<T, E extends Throwable> { void accept(T arg) throws E; } static class OptionalThrowable<E extends Throwable> { private Optional<E> value; public OptionalThrowable(Optional<E> value) { this.value = value; } public void rethrow() throws E { if (value.isPresent()) { throw value.get(); } } public E get() { return value.get(); } public boolean isPresent() { return value.isPresent(); } } }
run
|
edit
|
history
|
help
0
Nick-test
Table for 20
Three In A Row Solver
epeenconverter
Reverse a Linked List in groups of given size k
Fibonnaci + Prime number combined
Quadratic_Equation.java
Speed
Java
BiseccionJava