简体   繁体   中英

System.out.println doesn't work on a supplied Stream?

I'm still new to Java, and especially new to Suppliers, but I can't figure out why I can't get any output from the following code:

final BufferedReader brLines = new BufferedReader(new InputStreamReader(csvFile));
final Supplier<Stream<LinkedList<String>>> procLines = () -> brLines.lines().map(elm -> processCSV(elm));

lineCount = Math.toIntExact(procLines.get().count());

System.out.println(lineCount); // This prints the correct amount of lines to the console.

final CountDownLatch latch = new CountDownLatch(lineCount);

Stream<LinkedList<String>> listStream = procLines.get();
listStream.forEach((x) -> {
    System.out.println(x); // Why is there no console output here?
    outputText(() -> x); // Why is there no console output here either?

    ...
});

Here are some of the methods mentioned in this block

public static LinkedList<String> processCSV(String line) {  
    LinkedList<String> elms = new LinkedList<String>();
    char delimiter = ',';
    char quote = '"';

    String[] elmArray = splitCSVWithQuote(line, delimiter, quote).toArray(new String[0]);

    for (String elm : elmArray) {
        elms.add(elm);
    }

    return elms;
}

&

public static void outputText(Supplier sup) {
    System.out.println(sup.get());
}

Can anyone provide any help?

lineCount = Math.toIntExact(procLines.get().count());

count() is a terminal operation, it may traverse the stream to produce a result. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.

So you consumed all the lines of the file. So, the supplier can't give you again the stream since BufferedReader is now at the end-of-stream. That's why there is no output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM