Saturday, 19 July 2014

Java: lambdas, streams and IOException

The last post discussed exception handling with KλudJe in broad terms. This post presents a more practical example with the Stream type and I/O.

Streaming I/O Example

Here is a simple type that counts the number of lines in a collection of files:

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Map;
import static java.nio.charset.StandardCharsets.UTF_8;
import static;
import static uk.kludje.fn.function.UFunction.asUFunction;

/** Line counter - stream approach with checked exception handling. */
public class LineCounterDemo {

  public Map<Path, Long> countLines(Collection<? extends Path> paths) throws IOException {
        .collect(toConcurrentMap(p -> p, asUFunction(this::linesIn)));

  private long linesIn(Path path) throws IOException {
    try (Stream<String> lines = Files.lines(path, UTF_8)) {
      return lines.count();

The saving here is in the line .collect(toConcurrentMap(p -> p, asUFunction(this::linesIn)));. Without the UFunction type I/O exceptions would have to be wrapped and unwrapped with try/catch code. Note that IOExceptions must still be handled by callers because of the countLines method signature.

See the KλudJe documentation for more details on the above example.

No comments:

Post a Comment

All comments are moderated