unexpected String.join() behavior

  • A+
Category:Languages

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: