简体   繁体   中英

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 

Here list of files are considered as file array and processed one by one whereas string to char array conversion doesn't have effect in stream of method and is processed as a single string.

what I'm expecting is output for second code snippet should something like below as same as file stream processing.

Expected output:  
H  
e  
l  
l  
o  

h  
o  
w  

a  
r  
e  

y  
o  
u  

Much appreciated your help.

You are invoking two different overloads of Stream.of(..) :

Stream.of(T object)
Stream.of(T... objects)

toCharArray() returns a char[] which is not a T[] since primitive arrays are specific types different from a generic T[] (which is an Object[] under the hood).

So basically listFiles() return a File[] which matches the signature of(T... object) and produces a stream containing all the File instances while toCharArray() returns a char[] which matches of(T object) and returns a stream containing just that element.

Mind that String class already provides chars() method which returns an IntStream for your purpose:

"Hello how are you".chars().forEach(c -> System.out.println((char)c) }
"Hello how are you".chars().mapToObj(c -> (char)c).forEach(...)

The Stream.of(char[]) isn't going to work, because char is a primitive type. Instead, you can use an IntStream.range and then use that to get the characters. Like,

String line = "Hello how are you";
char[] chars = line.toCharArray();
IntStream.range(0, chars.length).forEachOrdered(i -> System.out.println(chars[i]));

Which matches your expected 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