How to implement a tree data-structure in Java?

前端 未结 24 2519
鱼传尺愫
鱼传尺愫 2020-11-22 00:27

Is there any standard Java library class to represent a tree in Java?

Specifically I need to represent the following:

  • The sub-tree at any node can have
24条回答
  •  梦谈多话
    2020-11-22 00:49

    In the past I have just used a nested map for this. This is what I use today, it is very simple but it fits my needs. Maybe this will help another one.

    import com.fasterxml.jackson.annotation.JsonValue;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.TreeMap;
    
    /**
     * Created by kic on 16.07.15.
     */
    public class NestedMap {
        private final Map root = new HashMap<>();
    
        public NestedMap put(K key) {
            Object nested = root.get(key);
    
            if (nested == null || !(nested instanceof NestedMap)) root.put(key, nested = new NestedMap<>());
            return (NestedMap) nested;
        }
    
        public Map.Entry put(K key, V value) {
            root.put(key, value);
    
            return (Map.Entry) root.entrySet().stream().filter(e -> ((Map.Entry) e).getKey().equals(key)).findFirst().get();
        }
    
        public NestedMap get(K key) {
            return (NestedMap) root.get(key);
        }
    
        public V getValue(K key) {
            return (V) root.get(key);
        }
    
        @JsonValue
        public Map getRoot() {
            return root;
        }
    
        public static void main(String[] args) throws Exception {
            NestedMap test = new NestedMap<>();
            test.put("a").put("b").put("c", 12);
            Map.Entry foo = test.put("a").put("b").put("d", 12);
            test.put("b", 14);
            ObjectMapper mapper = new ObjectMapper();
            System.out.println(mapper.writeValueAsString(test));
    
            foo.setValue(99);
            System.out.println(mapper.writeValueAsString(test));
    
            System.out.println(test.get("a").get("b").getValue("d"));
        }
    }
    

提交回复
热议问题