Java; go back up a file tree until a specific folder - java

I want to recursively go backwards up a directory until I find a specific parent folder.
Basically what I'm after is
while (!child.getParentFile().equals(greatGrandparent)) {
// keep going backwards until it does
}
Where child could be 10, 20, 50 levels underneath greatGrandparent
All I can find online is saying to start and grandparent and check each child until I find the child I'm looking for, but there could be a million children under the grandparent and I don't want to check them all when I know I just need to go back up the tree, if that makes sense.
Is there a standard pattern for this?

What's wrong with
while (!child.getParentFile().equals(greatGrandparent)) {
child = child.getParentFile();
}

Sounds like you are looking for simply this:
while (!child.getParentFile().equals(greatGrandparent)) {
child = child.getParentFile();
}
If this is not what you are looking for, you'll need to explain your problem better.

Related

How to update the value of a class instance in a ArrayList

ArrayList<Staff> allStaffs = new ArrayList<>();
allStaffs.add (new Staff("Jason", 1, "012323787", 987, 2300, "Computers"));
I want to update one of the fields in that instance. Like the name "Jason".
I kept figuring this out for myself but to no avail and also tried looking for other forums.
One possibility (probably not the most efficient) is to iterate through the list until you find the instance you want to update:
for(Staff staff : allStaffs){
if (staff.getName().equals("Jason")){
// here "staff" is that instance:
// staff....
}
}
If you know which element to change in the arraylist, simple get that elemnet as below and do something like this;
allStaffs..get(0).setName(0,"newJason")
Here 0 represents the index value of the element that needs to be changed.
This code is assuming that the Staff class contains a method called setName, and that "Jason" is being set as the name property of that Class.
Also, for future reference, when you say
"...I kept figuring this out for myself but to no avail and also tried looking for other forums."
It is always best to give an example of what you tried and what research was done by you. Also, it would be good if you share more of your code, like perhaps the Staff class which is what you are basically trying to change.
Hope you liked my answer. Please give a vote up if you did! :)

Get all siblings, previous and next in Magnolia/JCR-SQL2

Once you've gotten a node from the JCR, what is the easiest way to get its previous and next siblings?
Not entirely sure if its the easiest way but you may do something like that
Node parent = node.getParent();
NodeIterator siblings = parent.getNodes();
Node firstSibling = siblings.nextNode();
For previous you should do some operations on siblings object but that should be straightforward. This would be the JCR way of doing that.
However, Magnolia has the helper functions which reside under info.magnolia.jcr.util.NodeUtil package
Then One may use the following;
NodeUtil#getSiblingBefore()
NodeUtil#getSiblingAfter()

How to create a simple unordered tree(not BST) in java with given node pairs(u,v)?

Problem is I don't understand how to create a tree. I have gone through many code examples on trees but I don't even know how to work with/handle a node and hence I don't understand how the node class works(that was present in all the program examples ). When i try to use methods such as appendChild(as mentioned in java docs),I get an error,and I am asked to create one such appendChild method inside that node class within the main program. Couldn't understand why that happened.
I am given integer pairs((u,v) meaning there is an edge between u & v) of nodes and I also need to know if any Element-to-node conversion is required for using u and v(of type integer) as nodes.
Please bear with me since my basics are weak. Little explanation on how the entire thing works/functions would be very helpful.
Thank you.
EDIT 1: I went through the following links:(hardly found anything on just unordered trees) http://www.cs.cmu.edu/~adamchik/15-121/lectures/Trees/code/BST.java http://www.newthinktank.com/2013/03/binary-tree-in-java/ . Tried to modify these codes to meet my own purpose but failed.
I only got a blurry idea and that is not enough for implementation. I am trying to make a simple unordered tree,for which i am given u v pairs like:
(4,5) (5,7) (5,6). I just need to join (4<--5),(5<--7) and (5<--6). So how do I write a node class that only joins one node to the prev node? Besides,to do only this,do I need to bother myself with leftchild,rightchild? If not,how will I be able to traverse the tree and do similar operations such as height diameter calculation etc later?
Thank you for your patience.
Well Its not entirely clear whether you want an explanation on tree creation in general, on some tree implementation you have found, or you have a basic code already that you cannot get working. You might want to clarify that :).
Also tree creation in general:
Most explanation and implementation you will find might be "overly" elegant :). So try to imagine a simple linked list first. In that list you have nodes(the elements of the list). A node contains some valuable data and a reference to an other node object. A very simple tree is different only in that a node have more than one reference to other nodes. For example it has a Set of references, its "children".
Here is a VERY crude code only as an example for addChild() or appendChild in your case:
public class Node {
private String valueableData;
private Set<Node> children;
public Node(){
this.children=new HashSet<Node>();
}
public Node (String valueableData){
this.valueableData=valueableData;
this.children=new HashSet<Node>();
}
public void addChild(Node node){
children.add(node);
}
}
Now this implementation would be quite horrible (I even deleted the setter/getters), also it would be wise to keep the root nodes reference in some cases, and so on. But you might get the basic idea.
You might wanna create a cycle or recursion to go over the (u,v) integer pairs. You create the root node first then you just addChild() all the other nodes recursively, or create every node first then setChild() them according to your rules.

How to get descendants up to a certain level in a Tree?

Which Tree data structure in Java allows querying for different levels of children? I have looked at TreeNode, JTree. But they dont seem to support multi level querying.
Given a Tree, for a specific node, I want to get the descendants up to a certain level n. Is there an existing implementation that I can use or should I write my own?
Thanks!
It's not that hard to write a breadth-first traversal and visit all the children up to a specified level. Here is some pseudocode. Assume you have a new class:
public class NodeWithLevel {
Node node;
int level;
}
This class is only a wrapper used for this algorithm.
Then the "get all nodes up to level N" method would be:
Queue<NodeWithLevel> queue;
queue.enqueue(<0, tree.root>);
currentLevel = 0;
while(currentLevel < N) {
NodeWithLevel current = queue.dequeue();
currentLevel = current.level;
// do whatever with current
for(Node child: current.node.children) {
queue.enqueue(<current.level + 1, child>);
}
}
DefaultMutableTreeNode supports several traversals, using any one of them to reach your goal is left (no pun intended, it's by the api :) to the user.
If you're not afraid of a complex API, the DOM might be what you need. You can query it through XPath, apply events to its nodes, etc...
The only thing that springs to mind is swing's DefaultTreeModel but that would still require a bit of coding on your side for the logic to get children up to a certain level.
It shouldn't be too hard to roll your own implementation.

How to sort glazed TreeList?

I have a pretty weird question - how to sort glazed TreeList? I am using it in SWT NatTable, and when my data provider is set to GlazedListsDataProvider with TreeList inside it, sorting works in a very strange way. It works fine, if I am using GlazedListsDataProvider with SortedList.
For instance, my tree looks like that:
Root
Node1
Child1
Child2
Node2
Child3
I need to sort only children INSIDE Node1 and Node2, separately one of another (so that only child1 and child2 will change their place). However, After sorting it looks like following:
Root
Node1
Node2
Child1
Child2
Child3
Reversed sorting:
Root
Node1
Node2
Child2
Child1
Child3
So basically, it kind of working (it does sort children in a correct way), but moreover it sorts elements, which it should not sort. What could be a reason of such behavior? My sorting algorithm is simple:
compare (element1, element2) {
if (both elements are under same parent and have same type)
compare
otherwise
return 0
}
I am doing sorting as proposed in following example http://kari.dy.fi/src/sample/foldertree.zip - meaning, that after comparator is build in SortState I am setting it into the TreeFormat, used by TreeList.
I assume, that returning 0 does not work in a correct way, however, I can not see other solution. Or may be it is a problem somewhere else, not in my comparator.
Thank you for your patience, I will be glad to get any hints.
Best regards, Alex G.
Your current code returns 0 when to nodes have different parents. That's like, 'if they have different parents, I don't care which one goes first'. But I think you want, 'if they have different parents, the first should be the one with the first parent'. If you want to do custom sorting inside the parents only, you should keep sorting outside the parents the way it was. Not sure about the exact code, but you could do something like:
compare (element1, element2) {
if (both elements are under same parent and have same type)
compare
otherwise
return original.compare(element1,element2)//delegate to the original sorting
}
Or
compare (element1, element2) {
if (both elements are under same parent and have same type)
compare
otherwise
compare(element1.parent,element2.parent) // sort on parent level
}
So, here is my solution for this problem: DZone Article. Once again, it is only one of the possible solutions, and it is not perfect, but it is working:)

Categories