It was a really exciting moment as I heard that Java will get lambdas. The fundamental idea of using functions as a means of abstraction has its origin in the ‘lambda calculus’, 80 years ago. Now, Java developers are able to pass behavior using functions.
List<Integer> list = Arrays.asList(2, 3, 1);
// passing the comparator as lambda expression
Collections.sort(list, (i1, i2) -> i1 - i2);
// stream a list, sort it and collect results
Arrays.asList(2, 3, 1)
.stream()
.sorted()
.collect(Collectors.toList());
// a little bit shorter
Stream.of(2, 3, 1)
.sorted()
.collect(Collectors.toList());
// or better use an IntStream?
IntStream.of(2, 3, 1)
.sorted()
.collect(ArrayList::new, List::add, List::addAll);
// slightly simplified
IntStream.of(2, 3, 1)
.sorted()
.boxed()
.collect(Collectors.toList());
List.of(2, 3, 1).sort();
String getContent(String location) throws IOException {
try {
final URL url = new URL(location);
if (!"http".equals(url.getProtocol())) {
throw new UnsupportedOperationException(
"Protocol is not http");
}
final URLConnection con = url.openConnection();
final InputStream in = con.getInputStream();
return readAndClose(in);
} catch(Exception x) {
throw new IOException(
"Error loading location " + location, x);
}
}
Try:
Try<String> getContent(String location) {
return Try
.of(() -> new URL(location))
.filter(url -> "http".equals(url.getProtocol()))
.flatMap(url -> Try.of(url::openConnection))
.flatMap(con -> Try.of(con::getInputStream))
.map(this::readAndClose);
}
Success containing the content or a Failure containing an exception. In general, this notion is more concise compared to the imperative style and leads to robust programs we are able to reason about.
〜
I hope this brief introduction has peaked your interest in vavr! Please visit the site to learn more about functional programming with Java 8 and vavr. 