I have the following code to read a file in java, and prints out the lines. I implemented it in two ways:
using streams:
List<String> list = new ArrayList<>();
try (BufferedReader br = Files.newBufferedReader(file.toPath())) {
list = br.lines().collect(Collectors.toList());
Map<String, Long> totalCount = list.stream() .....
Using loops:
try (FileReader reader = new FileReader(file);
final BufferedReader bufferedReader = new BufferedReader(reader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {.. }
I was told this is the wrong, and using buffered reader is using features of the language wrongly. Is there a better way to this, i want to the know the correct way to use the language features.
CodePudding user response:
These two examples do two slightly different things. The key difference is that the first solution first reads all lines into memory, before then iterating the lines.
The second example reads the file line by line, this means that its content can be processed line by line.
First way: easy to write, read, and understand. But: as said, it reads the whole file into memory. Which isn't a problem for small files, but for really large files, this can create all kinds of issues (it takes time to read a large file, and you might run out of memory for really large files).
The other differences between the two approaches are somehow more "style", where: br.lines()
already gives you a Stream
, it doesn't make any sense to first collect the lines into a List object, to then stream that one.