{demo=[ServiceInstance(appSymbol:demo,appIp:127.0.0.1),ServiceInstance(appSymbol:demo,appIp:127.0.0.2)]}转换成树结构Java代码
时间: 2024-05-14 14:15:26 浏览: 63
127.0.0.1无法访问,没有权限: GetObject
5星 · 资源好评率100%
以下是将{demo=[ServiceInstance(appSymbol:demo,appIp:127.0.0.1),ServiceInstance(appSymbol:demo,appIp:127.0.0.2)]}转换成树结构的Java代码:
```
import java.util.*;
class Node {
String name;
List<Node> children;
public Node(String name) {
this.name = name;
children = new ArrayList<>();
}
}
public class Main {
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<>();
map.put("demo", Arrays.asList("ServiceInstance(appSymbol:demo,appIp:127.0.0.1)", "ServiceInstance(appSymbol:demo,appIp:127.0.0.2)"));
Node root = new Node("root");
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
String key = entry.getKey();
List<String> values = entry.getValue();
Node node = new Node(key);
for (String value : values) {
Node child = new Node(value);
node.children.add(child);
}
root.children.add(node);
}
printTree(root, 0);
}
private static void printTree(Node node, int depth) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < depth; i++) {
sb.append("-");
}
sb.append(node.name);
System.out.println(sb.toString());
for (Node child : node.children) {
printTree(child, depth + 1);
}
}
}
```
输出结果:
```
-root
--demo
---ServiceInstance(appSymbol:demo,appIp:127.0.0.1)
---ServiceInstance(appSymbol:demo,appIp:127.0.0.2)
```
阅读全文