I tried to print contents of a List<String>
with a "," in between them. Followed the book Functional Programming in Java by Venkat Subramaniam, on page 54 , he did exactly what I am doing but my print result is coming as a single string without a comma(,)
.
String[][] deepArrayStr = new String[][]{{"Alex", "nullpointer"}, {"Eran", "George"}};
List<String> str= Arrays.stream(deepArrayStr)
.flatMap(Arrays::stream)
.collect(Collectors.toList());
for(String s:str){
System.out.print(String.join(",",s));
}
Output: AlexnullpointerEranGeorge
Expected: Alex,nullpointer,Eran,George
I tried another way and it works fine, I just wanted to know is there anything that I am doing wrong in the above approach whereas in the book Venkat also did the same thing that I am doing?
System.out.println(Arrays.stream(deepArrayStr)
.flatMap(Arrays::stream)
.collect(Collectors.joining(",")));
Output: Alex,nullpointer,Eran,George
Expected: Alex,nullpointer,Eran,George
My question is not to convert from List
to string
but to add delimiter while printing.
You're iterating over the list, and calling String.join
with a single entry each time. That's never going to use the delimiter.
To make this clear, consider these two examples:
String x1 = String.join(",", "a");
String x2 = String.join(",", "a", "b");
Then the value of x1
will be "a", and the value of x2
will be "a,b". String.join
only adds the delimiter between items - so if you only pass it a single item, it doesn't need to add any delimiters.
You can just remove your for
loop, and replace it with:
System.out.println(String.join(",", str));
System.out.print(String.join(",",s));
You are passing a single String
to each String.join
call, so of course it won't add any delimiter. It only adds the delimiter (comma in your case), if you pass multiple String
s.
If, for example, you'd collect your Stream
into a String
array instead of a List
, you can pass that array to String.join
:
String[] str = Arrays.stream(deepArrayStr)
.flatMap(Arrays::stream)
.toArray(String[]::new);
System.out.println (String.join (",", str));
This will output:
Alex,nullpointer,Eran,George
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With