0

I'm reading lines from a zipped input stream, and I need to filter it by the first 4 positions (a period). Is is possible to use a lambda (like the filter in streams) to avoid the condition?

private List<String> readlinesByPeriod(DPeriod period, ZipInputStream zis) throws IOException {
    List<String> lines = new ArrayList();

    byte[] data = SCIOUtils.readData(zis);
    InputStream is = new ByteArrayInputStream(data);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, CharEncoding.ISO_8859_1));
    String line;
    while ((line = reader.readLine()) != null) {
        String periodCode = StringUtils.substring(line, 0, 4);
        if (periodCode.equals(period.getCode())) {
            lines.add(line);
        }
    }

    return lines;
}

1 Answer 1

1

Yes, it's possible

return reader.lines()
    .filter(line -> StringUtils.substring(line, 0, 4).equals(period.getCode()))
    .collect(Collectors.toList());

It's worth noting that the JavaDoc for BufferedReader.lines says

If an IOException is thrown when accessing the underlying BufferedReader, it is wrapped in an UncheckedIOException which will be thrown from the Stream method that caused the read to take place

So if you want your method to continue to throw a checked exception (IOException or otherwise), then you'd have to wrap the above in a try-catch block for UncheckedIOException and wrap it and rethrow as a checked exception.

Sign up to request clarification or add additional context in comments.

2 Comments

I found that BufferedReader has a lines method which returns a Stream, I used: return reader.lines() .filter(line -> line.startsWith(period.getCode())) .collect(Collectors.toList());
@LluisMartinez Oh, good find. I learned something today. I didn't think they'd bothered to retrospectively add stream support to classes like BufferedReader. Updated my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.