简体   繁体   English

如何将属性文件中的空值添加到 Map

[英]How to add null value from a properties file to Map

I have a properties file, the content of which are as follows我有一个properties文件,其内容如下

test=uri=someURI,uname=username,pwd=

The parameters are separated by a comma, and the key and values are separated by = I'm using ResourceBundle.getBundle("fileName") to read the file and getString("test") method to read the entry for test .参数用逗号分隔,键和值用=分隔我使用ResourceBundle.getBundle("fileName")读取文件,使用getString("test")方法读取test的条目。

What I'm trying to to here is get the strings separated by = inside a Map, using the following method.我在这里尝试的是使用以下方法在 Map 中获取由=分隔的字符串。

public static Map<String, String> configMap(String entry) {
    return Arrays.stream(rb.getString(entry).split(",")).map(e -> e.split("="))
            .collect(Collectors
                    .toMap(keyValue -> keyValue[0].trim(), keyValue -> keyValue[1].trim(), (a, b) -> b));
}

The methods works in a weird manner though.不过,这些方法的工作方式很奇怪。 In the properties file, if I assign a space as a value for pwd , it works fine, but if I assign nothing to pwd , not even a space, it gives me the following error在属性文件中,如果我为pwd分配一个空格作为值,它可以正常工作,但是如果我没有为pwd分配任何内容,甚至没有分配一个空格,它会给我以下错误

java.lang.ArrayIndexOutOfBoundsException: 1

The Map needs to accept null values too, how can I implement that? Map 也需要接受空值,我该如何实现?

Your can check the length of the keyValue array, and if it doesn't have a second element - put an empty String in the Map .您可以检查keyValue数组的长度,如果它没有第二个元素 - 在Map放置一个空String

Unfortunately you can't put a null value in the Map when using Collectors.toMap() .不幸的是,在使用Collectors.toMap()时,您不能在Map放置null值。

return Arrays.stream(rb.getString(entry).split(",")).map(e -> e.split("="))
        .collect(Collectors
                .toMap(keyValue -> keyValue[0].trim(), 
                       keyValue -> keyValue.length > 1 ? keyValue[1].trim() : "", 
                       (a, b) -> b));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM