首页 > 解决方案 > 字符串连接空值并检索空值java

问题描述

我正在使用 Stream.of 将几个字符串值与分隔符“:”连接起来,其中一个可以为空,但是当我将它检索到字符串数组时,我希望其中有固定数量的元素大批。我想知道字符串数组中的哪一个为空。例如,我通过使用连接了一个字符串

Stream.of("abc", "def", "ghi", null)
            .collect(Collectors.joining(":"));

它将是“abc:def:ghi:null”。然后将其拆分为字符串数组,我使用

final String[] strings = "abc:def:ghi:null".split(":");

但是字符串 [3] 是“null”而不是 null。有没有办法将“null”转换为空值?

标签: javaarraysregexjava-8stream

解决方案


您应该将null映射作为后处理处理:

String[] strings =  "abc:def:ghi:null".split(":");
strings = Arrays.stream(strings).map(s-> s.equals("null")? null : s).toArray(String[]::new);
System.out.println(strings[3] == null);

打印true

请注意,在这里您不知道是否在流中的原点使用null"null"String ,因为一旦加入 String ,您就无法区分它们。


推荐阅读