Java 8 Stream read file for every 100 lines

Viewed 5874

Let's say I have a huge file and I would like to read 100 every lines and do one operation. (I want to combine 100 lines and send a rest request)

In Java 7, I would do something like below.

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

    String line;
    int count = 0;
    List<String> list = new ArrayList<>();       
    while ((line = br.readLine()) != null) {
        list.add(line);
        count++;
        if (count % 100 == 0) {
            //do the operation on list
            list = new ArrayList();
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

Is there something we can leverage Java 8 Stream here? I know we can do something like this but it operates on each line instead of 100 lines. So I think foreach is not the option here.

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    stream.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}
2 Answers
Related