[英]How to build a Java 8 stream from System.in / System.console()?
給定一個文件,我們可以使用例如,將其轉換為字符串流
Stream<String> lines = Files.lines(Paths.get("input.txt"))
我們能否以類似的方式從標准輸入構建一條線流?
kocko答案的匯編和Holger的評論:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Stream<String> stream = in.lines().limit(numberOfLinesToBeRead);
你可以將Scanner
與Stream::generate
結合使用:
Scanner in = new Scanner(System.in);
List<String> input = Stream.generate(in::next)
.limit(numberOfLinesToBeRead)
.collect(Collectors.toList());
或者(如果用戶在達到限制之前終止,則避免NoSuchElementException
):
Iterable<String> it = () -> new Scanner(System.in);
List<String> input = StreamSupport.stream(it.spliterator(), false)
.limit(numberOfLinesToBeRead)
.collect(Collectors.toList());
通常標准輸入是逐行讀取的,因此您可以做的是將所有讀取行存儲到集合中,然后創建對其進行操作的Stream
。
例如:
List<String> allReadLines = new ArrayList<String>();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = in.readLine()) != null && s.length() != 0) {
allReadLines.add(s);
}
Stream<String> stream = allReadLines.stream();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.