How do I locate or get parent of child in tree - java

I am making a tree from a text file like this:
Store, manager, employee
manager, smith, Michael
employee, steve, karen, litt, kwan
my code is something like this:
reads first line;
sets first string to parent and following to children
reads second line, sets first string to parent and following to children
But I want to read the second line, see if the first string is children in above string, and assign the value the first string(parent of second line) to that children to achieve a tree structure like this:
Store
/
manager - employee
/ \
smith - Michael steve - karen - litt - kwan
I cannot figure out the part where I check if the parent of the string is a child of any previous string and set it to that child

You can use a HashMap.
Suppose you have a Node class like this:
class Node{
String value;
Node parent;
Node[] children;
}
When you construct you tree,You can construct a HashMap<String,Node> to map the string value to the Node Object.
Then you can check map.get(stringValue)==null to see if the stringValue is a child of above String.

Related

How to find children of children's context in ANTLR?

As the title say, is there a way to find the children of children node when listen or visit a node in ANTLR.
For example: (use grammars-v4-java lexer and parse rule)
First, I take a java file to grammar tree.
grun Java compilationUnit -gui Example.java
// Example.java
public class Example {
String name = "test";
void call(){
String name1 = "test";
}
}
and the grammar tree is
Then I try to use java to extends the baseListerner to listen enterClassDeclaration node. So I can get the ClassDeclarationContext node. I want to find the ClassDeclarationContext node's children of children that the child type is LocalDeclarationContext.
In this example:
public class MyListener extends JavaParserBaseListener {
#Override
public void enterClassDeclaration(JavaParser.ClassDeclarationContext ctx) {
// find the children of children by ctx
List<ParserRuleContext> contexts = findChildContextBy(ctx, LocalVariableDeclarationContext.class);
super.enterClassDeclaration(ctx);
}
}
The variable contexts should has two elements. name and name1
I do not want to find the children one layer by one layer. emmm, Is there have a convenient way?
For a given parse tree it's easy to look up specific child nodes (at any nesting level) using ANTLR4's XPath implementation.
You can trigger that search from either the full parse tree return by the called parser rule or within a listener/visitor method for the particular subtree, for example:
List<ParseTreeMatch> matches = XPath.findAll(ctx, "//localVariableDeclaration", parser);
The return matches are instances of LocalVariableDeclarationContext (if any matched).
Note: the linked page describe two search utilities, parse tree matching and XPath, which can be used individually or together.

To Implement Parent/Child & get Set of records If i give parent name

I have data as shown as below. Here if Team 1 is parent & having 2 child Team A & Team B. Team A is again a parent & having player names as child. Team B does not have any child.
Again in another scenario, Team A is independent parent & contains some child etc..
If i give Team 1, then it should fetch records of Team A & Team B as a bundle.
If i give Team A, then it should fetch records of Team A containing its child.
I was thinking to implement this using Map or Tree . and I tried this -
public class Node {
private String id;
private List<Node> children = new ArrayList<>();
private Node parent;
..........
//setters and getters
}
but here creating node dynamically is problem because we don't know the levels of parents(in this example there are 2). means "Dhoni" again contains some child like wise.
How to implements this ?. Please guide.
Whatever i understood from problem description i will try to summarize here.You are looking for a data structure which can take parent name(key) and it might have children, and each child also further can be extended.
public class Node {
private String id; // for each level you have key defined.
private List<Node> children = new ArrayList<>(); //using given key you can get children list
}
You can use map here
Map<String, List<Node>> // here key is team name etc., and list represents children.
If you give team1 as key, you get list which contains teamA, teamB. So if you want to check further, check list size, if it is greater than zero, you can get children(Further you can get all the players defined for both teamA,teamB) otherwise you are at last child.

data modeling in spring-data-neo4j

My graph contains nodes called points and lines.
There is a relationship type called "NEXT", which connects two points and has a property called lineID (a long). A line node consists simply of an ID and a reference to a "root" point. To traverse a line is to start with its root node and follow the NEXT relationships whose lineID matches the id of the line being traversed. To clarify, if we're traversing a line with ID 123, whose root point has id 321, the Cypher traversal would be:
START n = node(321)
MATCH (n)-[rel:NEXT*{lineID:123}]->(x)
RETURN collect(rel)
A line, then, is essentially a linked list of Next relationships with matching lineID properties. That said, I don't want to persist this list as a property of lines - I want the list to be constructed by a traversal when a line is loaded.
What are my options for implementing this in spring-data-neo4j? Specifically, should "lines" exist as NodeEntitys, and if so what should they contain?
#NodeEntity
class Line {
#RelatedTo(type="ROOT")
Point root;
#RelatedToVia(type="NEXT")
Iterable<Item> list;
doesn't quite fit, because the line is not related via Next relationships to the item, the root point is. It also fails to address the fact that those NEXT relationships need to have a lineID property matching the line's ID (which becomes important because some points exist on multiple lines - i.e. they have multiple NEXT relationships with different lineID's). I have a hunch that the solution will involve annotating the list as a #GraphTraversal, but I don't understand how that would work.
I'm doing this largely as an exercise to wrap my head around data modeling in SDN, in the context of wrapping my head around Neo4j and graph databases in general. If the question I'm asking reveals a flaw in my understanding of any of these things, I'd be very appreciative if someone could point it out.
This should be a suitable model for your entities:
#NodeEntity
class Point {
#GraphId
protected Long id;
#RelatedToVia(type="NEXT")
Set<Edge> edges;
}
#NodeEntity
class Line {
#GraphId
protected Long id;
#RelatedTo(type="ROOT")
Point root;
}
#RelationshipEntity
public class Edge {
#GraphId
protected Long id;
#StartNode private Point from;
#EndNode private Point to;
#RelatedTo(type="LINE")
Line line;
}
It easily allows both programmatic navigation in Java as in:
Set edges = line.getPoint().getEdges();
for (Edge edge: edges) {
if (edge.getLine().getId() == id) {
...
}
}
or Cypher queries like the one you listed.

Generate Nested List (Tree) from Flat List

I have a plain class named MenuModel in Java (it's for nested menu as the name suggests) like this:
public class MenuModel {
public String id;
public String parentId = null;
public String title;
public MenuModel parent = null;
public List<MenuModel> children = new ArrayList<MenuModel>();
}
My code fetch data from web API and generate a flat list of MenuModel with only id, parentId, and title fields filled with data. However, I need each MenuModel to have references to its parent and (optionally) children for further uses.
I have thought of a method which make a nested loop to pair the models each other and check if they are parent and child. But I think that costs too much (n^2 or n^3 complexity, the itemset is large) and can only fill the parent field.
What is the best way to achieve this in Java? To summarize:
Input: ArrayList<MenuModel> source
Output: ArrayList<MenuModel> result containing all MenuModel from source which has parentId = null (that means, it's top level menu), with each MenuModel has children fields filled with reference to their respective children MenuModel. Additionally, each children have reference to their parents.
Thanks in advance
Go through all the records and add them to a HashMap<String, MenuModel> (the key being the ID).
Then, for each record record:
Look up the parent ID in the above map to get parent.
Assign the parent to this record's parent variable - record.parent = parent.
Add this record to the parent's list of children - parent.children.add(record).
Running time: Expected O(n).

How to get a specific JTree node given a string array

If I have a String[] such as { "root", "two", "1" } how can I get the DefaultMutableTreeNode from my JTree that is represented by this "path"?
For example if my JTree looks like this:
root
one
1
2
two
1 <-- I want this node
2
Assume all nodes are DefaultMutableTreeNodes.
First, you need to fetch the tree model with getModel() method. Once you have the model, it has the getRoot() method, to fetch the root of the tree. After that, you can follow with calls to getChild(Object parent, int index) and check if any of the children has the same name as the one provided in the String array. If you find such one, you can again call getChild(Object parent, int index), etc... until you arrive at the last String from the array. Then you have the corresponding tree node. You need to actually cast the tree nodes to DefaultMutableTreeNode, as the TreeModel uses Object as the tree elements (for pre-1.7 Java).

Categories

Resources