Search code examples
javafilejava-stream

Is Files.lines().allMatch() ordered? Attempting to find first three consecutive lines which each match different criteria


I'm trying to get away from while ((line = br.readLine()) != null), but the limitations of streams are proving to be hard to overcome in an elegant way in this case.

I want the first line which matches a certain criterion and the last two lines before this which matches two different criteria. This seems to be the best I can do, but it only works if lines are encountered in the right order so it doesn't terminate early. So are they? It's hard to tell from the documentation.

String[] savedLines = { "", "", "" };
try (Stream<String> lines = Files.lines(file)) {
    lines.allMatch(line -> {
        if (line.startsWith(s1)) {
            savedLines[0] = line;
        } else if (line.startsWith(s2) && line.contains(s3)) {
            savedLines[1] = line;
        } else if (line.startsWith(s4)) {
            savedLines[2] = line;
            return false;
        }
        return true;
    });
}

Solution

  • Given that the lines are being read from a file, I can't see why they wouldn't be in file order - it would take more storage to do anything other than read the current line, then read the next line etc.

    Irrespective, don't do it like this: you are going against what it says in the documentation about the predicate of Stream.allMatch:

    predicate - a non-interfering, stateless predicate to apply to elements of this stream

    Your predicate is not stateless. You shouldn't do this in allMatch.

    Stick with BufferedReader.