Find a value for a specific key in a linked hashmap in java

Is there a simpler way to find a value for a specific key in a linked hash map in Java?

HashMap<String, Object> newmap = (HashMap<String, Object>) entry.getValue();
String newType = "";
//finds out the primaryType for the new node
for (Entry<String, Object> mapentry : newmap.entrySet()) {
    if (mapentry.getKey() == "jcr:primaryType") {
        newType = (String) newmap.get("jcr:primaryType");
    }
}

3 answers

  • answered 2020-01-14 12:29 Mohammed Deifallah

    LinkedHashMap<String , Object> newmap = (LinkedHashMap<String, Object>) entry.getValue();
    String newType = (String) newmap.getOrDefault("jcr:primaryType", "");
    

  • answered 2020-01-14 12:32 daniu

    Since your default result is "", you can do

    String newType = newmap.getOrDefault("jcr:primaryType", "");
    

  • answered 2020-01-14 12:49 Ducaz035

    All the answers above are correct if we are talking about pure Map perspective but in JCR or Magnolia; you can use javax.jcr.Node#getProperty

    To query the Node object for a particular property, one might use; javax.jcr.Node#hasProperty