1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 package ohos.devtools.views.applicationtrace.bean; 17 18 import java.util.HashMap; 19 import java.util.List; 20 import java.util.Map; 21 22 /** 23 * tree node to tree 24 * 25 * @param <T> data type 26 * @since 2021/5/19 16:39 27 */ 28 public abstract class TreeNodeToTree<T> { 29 /** 30 * get key 31 * 32 * @param node node 33 * @return key 34 */ getKey(T node)35 protected abstract String getKey(T node); 36 37 /** 38 * get parent node id 39 * 40 * @param node node 41 * @return parent id 42 */ getParentId(T node)43 protected abstract String getParentId(T node); 44 45 /** 46 * add childes 47 * 48 * @param node node 49 * @param parent parent node 50 */ addChildrens(T node, T parent)51 protected abstract void addChildrens(T node, T parent); 52 53 /** 54 * add root node 55 * 56 * @param node root node 57 */ addRootNode(T node)58 protected abstract void addRootNode(T node); 59 60 /** 61 * list to tree 62 * 63 * @param list data list 64 */ listToTree(List<T> list)65 public void listToTree(List<T> list) { 66 Map<String, T> newMap = new HashMap<>(); 67 for (T tree : list) { 68 newMap.put(getKey(tree), tree); 69 } 70 for (T tree : list) { 71 T parent = newMap.get(getParentId(tree)); 72 if (parent != null) { 73 addChildrens(tree, parent); 74 } else { 75 addRootNode(tree); 76 } 77 } 78 } 79 } 80