forked from winterbe/java8-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckedFunctions.java
More file actions
92 lines (84 loc) · 2.39 KB
/
CheckedFunctions.java
File metadata and controls
92 lines (84 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.winterbe.java8.samples.misc;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* Utilities for hassle-free usage of lambda expressions who throw checked exceptions.
*
* @author Benjamin Winterberg
*/
public final class CheckedFunctions {
@FunctionalInterface
public interface CheckedConsumer<T> {
void accept(T input) throws Exception;
}
@FunctionalInterface
public interface CheckedPredicate<T> {
boolean test(T input) throws Exception;
}
@FunctionalInterface
public interface CheckedFunction<F, T> {
T apply(F input) throws Exception;
}
/**
* Return a function which rethrows possible checked exceptions as runtime exception.
*
* @param function
* @param <F>
* @param <T>
* @return
*/
public static <F, T> Function<F, T> function(CheckedFunction<F, T> function) {
return input -> {
try {
return function.apply(input);
}
catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
};
}
/**
* Return a predicate which rethrows possible checked exceptions as runtime exception.
*
* @param predicate
* @param <T>
* @return
*/
public static <T> Predicate<T> predicate(CheckedPredicate<T> predicate) {
return input -> {
try {
return predicate.test(input);
}
catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
};
}
/**
* Return a consumer which rethrows possible checked exceptions as runtime exception.
*
* @param consumer
* @param <T>
* @return
*/
public static <T> Consumer<T> consumer(CheckedConsumer<T> consumer) {
return input -> {
try {
consumer.accept(input);
}
catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RuntimeException(e);
}
};
}
}