在Collectors.joining中避免对空字符串使用前缀和后缀的方法是在使用Collectors.joining方法之前检查待连接的字符串是否为空,如果为空则不添加前缀和后缀。
下面是一个示例代码:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List strings = Arrays.asList("hello", "", "world", "");
String result = strings.stream()
.filter(s -> !s.isEmpty()) // 过滤掉空字符串
.collect(Collectors.joining(", "));
System.out.println(result);
}
}
这里使用了stream的filter方法来过滤掉空字符串,然后再使用Collectors.joining方法进行字符串的连接。在filter方法中,我们使用了!s.isEmpty()来判断字符串是否为空,如果为空则不会被包含在连接的结果中。
输出结果为:
hello, world
这样就避免了对空字符串使用前缀和后缀。