[英]Java Stream not working as expected in Character or Byte array
// code snippet 1:-
Stream.of(Paths.get("/tmp").toFile().listFiles()).forEach(System.out::println);
output:
/tmp/.keystone_install_lock
/tmp/.vbox-srirammuthaiah-ipc
/tmp/a.txt
/tmp/b.txt
/tmp/com.apple.launchd.1enUeBRkSj
/tmp/com.apple.launchd.KIcK6WPwWH
/tmp/mbbservice.pid
/tmp/mv.txt
/tmp/wifi-12-03-2016__18:16:24.log
// code snippet 2:-
String line = "Hello how are you";
Stream.of(line.toCharArray()).forEach(System.out::println);
output:
Hello how are you
在這里,文件列表被視為文件數組,並被一個接一個地處理,而字符串到字符數組的轉換在方法流中不起作用,而是作為單個字符串處理。
我期望的是第二個代碼段的輸出,如下所示,與文件流處理相同。
Expected output:
H
e
l
l
o
h
o
w
a
r
e
y
o
u
非常感謝您的幫助。
您正在調用Stream.of(..)
兩個不同的重載:
Stream.of(T object)
Stream.of(T... objects)
toCharArray()
返回一個char[]
,它不是T[]
因為原始數組是與通用T[]
(在toCharArray()
為Object[]
)不同的特定類型。
因此,基本上listFiles()
返回一個與File[]
of(T... object)
簽名匹配的File[]
並生成包含所有File
實例的流,而toCharArray()
返回一個與of(T object)
匹配of(T object)
char[]
並返回一個僅包含該元素的流。
注意String類已經提供了chars()
方法,該方法返回一個IntStream
供您使用:
"Hello how are you".chars().forEach(c -> System.out.println((char)c) }
"Hello how are you".chars().mapToObj(c -> (char)c).forEach(...)
Stream.of(char[])
不起作用,因為char
是原始類型。 相反,您可以使用IntStream.range
,然后使用它來獲取字符。 喜歡,
String line = "Hello how are you";
char[] chars = line.toCharArray();
IntStream.range(0, chars.length).forEachOrdered(i -> System.out.println(chars[i]));
哪個符合您的預期輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.