如何在Map <string,map <string,string =“” >>结构上使用getProperty()

时间:2019-04-19 11:32:14

标签: java

我已使用以下代码创建了属性对象-

import java.util.*;

public class setPropertyTest {
   public static void main(String[] args) {

       Map<String, String> mp1 = new HashMap<>();
       mp1.put("from", "somethingfrom");
       mp1.put("to", "somethingTO");

       Map<String, Map<String,String>> mp2 = new HashMap<>();
       mp2.put("testing", mp1);

       Properties properties = new Properties();
       properties.putAll(mp2);


   }
}

当我打印属性时,它会打印到以下内容-

{testing={from=somethingfrom, to=somethingTO}}

如何从属性对象中检索from键值?

3 个答案:

答案 0 :(得分:1)

here所述,并由@ernest_k评论,“属性”设计用于键是字符串且值也是也是字符串的情况。

要实现您想要的目标,请尝试:

mp2.get("testing").get("from");

答案 1 :(得分:1)

这是NPE安全的方法。 getOrDefault来自Java 8

mp2.getOrDefault("testing", Collections.emptyMap()).get("from")

答案 2 :(得分:0)

按照OP的要求,要从Property对象"from"获取(properties)的键值,我们可以做类似的事情

    Properties properties = new Properties();
    properties.putAll(mp2);
    Object obj = properties.get("testing");
    if (obj instanceof Map) {
        Map<String,String> innerMap = ((Map<String, String>) obj);
        innerMap.get("from");
    }