【问题标题】:System.out.println doesn't work on a supplied Stream?System.out.println 在提供的 Stream 上不起作用?
【发布时间】:2020-08-06 16:00:24
【问题描述】:

我还是 Java 新手,尤其是 Suppliers 新手,但我不明白为什么我无法从以下代码中获得任何输出:

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?

    ...
});

以下是本块中提到的一些方法

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());
}

谁能提供帮助?

【问题讨论】:

  • 我很确定你已经使用了所有的行,并且从现在为空的行列表中创建一个新的 Stream 并没有返回它们。

标签: java arrays queue consumer supplier


【解决方案1】:
lineCount = Math.toIntExact(procLines.get().count());

count()是终端操作,它可能会遍历流产生结果。终端操作执行后,流管道被视为消耗,不能再使用。

所以你消耗了文件的所有行。因此,供应商不能再给你流,因为BufferedReader 现在位于流的末尾。这就是没有输出的原因。

【讨论】:

  • 是的,它正在被消耗。我认为Supplier 为每个.get() 提供了流的新副本,但我猜不是。
  • @Mbgm 使用的Supplier 每次都会创建一个新的Stream,所以这不是问题。问题是相同的BufferedReader 被用作源。换句话说,在第一个流之后,BufferedReader 现在位于流的末尾,而第二个流没有要遍历的元素。
猜你喜欢
  • 1970-01-01
  • 2017-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 1970-01-01
  • 2014-10-18
相关资源
最近更新 更多