NikonJR NikonJR -4 years ago 154
Java Question

How to get specific key value from a nested TreeMap

Say I have the TreeMap,

TreeMap<String,TreeMap<String,TreeMap<String,String>>> map = new TreeMap<>();


and there are two values,

mapToTree("1","1","1","111");
mapToTree("1","2","111",null);


where mapToTree is a method for storing values into the nested TreeMap.

I know that to get a value that is in the last value position I would do,

map.get("1").get("1").get("1");


but how would I get the key value in 1,2? Currently when I do

System.out.println(map.get("1").get("2"));


it prints "{111=null}."

Answer Source
  1. You can get the entire keySet and iterate

    map.get("1").get("2").keySet().forEach(System.out::println);
    
  2. For the case if you are only interested in the first key, value pair you can use -

    System.out.println(map.get("1").get("2").firstKey());
    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download