Home > Blockchain >  Java: Processing Stream line by line without forEach?
Java: Processing Stream line by line without forEach?

Time:12-02

I am new to Java and trying out Streams for the first time.

I have a large input file where there is a string on each line like:

cart
dumpster
apple
cherry
tank
laptop
...

I'm trying to read the file in as a Stream and doing some analysis on the data. For example, to count all the occurrences of a particular string, I might think to do something like:

Stream<String> lines = Files.lines(Path.of("/path/to/input/file.txt"));
int count = 0;

lines.forEach((line) => {
    if (line.equals("tank")) {
        count  ;
    }
});

But, Java doesn't allow mutation of variables within the lambda.

I'm not sure if there's another way to read from the stream line by line. How would I do this properly?

CodePudding user response:

You don't need a variable external to the stream. And if you have a really big file to count, long would be preferred

long tanks = lines
    .filter(s -> s.equals("tank"))
    .count();

CodePudding user response:

To iterate a stream using a regular loop, you can get an iterator from your stream and use a for-loop:

Iterable<String> iterable = lines::iterator;
for (String line : iterable) {
    if (line.equals("tank")) {
           count;
    }
}

But in this particular case, you could just use the stream's count method:

int count = (int) lines.filter("tank"::equals).count();

CodePudding user response:

you can read from the file line by line, with stream of each one :

    try (Stream<String> lines = Files.lines(Path.of("/path/to/input/file.txt"))) {
        list = stream
                .filter(line -> !line.startsWith("abc"))
                .map(String::toUpperCase)
                .collect(Collectors.toList());

    } catch (IOException e) {
        e.printStackTrace();
    }
  •  Tags:  
  • java
  • Related