Java Stream How to - Process file with lambda








Question

We would like to know how to process file with lambda.

Answer

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
// w ww  . j  a v a 2s  .com
    public static void main(String ...args) throws IOException{
        String oneLine = processFile((BufferedReader b) -> b.readLine());
        System.out.println(oneLine);

        String twoLines = processFile((BufferedReader b) -> b.readLine() + b.readLine());
        System.out.println(twoLines);

    }
    public static String processFile(BufferedReaderProcessor p) throws IOException {
        try(BufferedReader br = new BufferedReader(new FileReader("lambdasinaction/chap3/data.txt"))){
            return p.process(br);
        }

    }
}
interface BufferedReaderProcessor{
  public String process(BufferedReader b) throws IOException;

}