Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected String.join() behavior

Tags:

java

java-8

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.

like image 509
Vishwa Ratna Avatar asked Nov 26 '22 23:11

Vishwa Ratna


2 Answers

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));
like image 87
Jon Skeet Avatar answered Dec 30 '22 05:12

Jon Skeet


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 Strings.

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
like image 22
Eran Avatar answered Dec 30 '22 06:12

Eran