Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to create a Java tree, ordred by string path

I have a list of string path like this :

{"/foo", "/bar", "/foo/admin", "/foo/cust", "/bar/erp", "/bar/erp/call", "/foo/cust/profile"}

How to create an ordred string tree path? Or Where can I find a kind of library that can resolve my problems?

the other part, is that I want to know how to loop against the structure the fetch the informations that I need (e.g A tree node will contain a string path but can also contain a collection of object with a path attribute) so you can understand that a need a complex data structure

The tree can be represented like this:

- /
-- /foo
-- -- /foo/admin
-- -- /foo/cust
-- -- -- /foo/cust/profile
-- /bar
-- -- /bar/erp
-- -- -- /bar/erp/call

Thanks

like image 287
TheCyberXP Avatar asked Jul 18 '12 14:07

TheCyberXP


2 Answers

What you need:

  1. A main loop that iterates through the array of strings 1 at a time from the beginning to the end.
  2. A tokenizer function that splits a path such as /foo/bar/sid into an array of strings {'foo','bar','sid'}.
  3. A tree structure (if you don't know how to represent trees in memory, check out this java how-to: http://vivin.net/2010/01/30/generic-n-ary-tree-in-java/ but it would be beneficial to look at a language independent guide as well because it would give you a good overview of the theory behind it: http://people.cis.ksu.edu/~schmidt/300s05/Lectures/Week7b.html). The top of your tree should be something like 'root' as foo and bar should both be under the same tree.

How to use these together: Iterate through the main array in 1., passing each string to the tokenizer in 2. one at a time. Use the new tokenized string to go through the tree using the first token as the first level of the tree, second as the second, etc. as you encounter tokens that don't exist in the tree, add them.

After building the tree, you simply iterate through it a branch at a time echoing out its contents.

Cheers, and happy coding!

like image 177
retrohacker Avatar answered Sep 24 '22 04:09

retrohacker


try this:

import java.util.*;

public class Main {
public static void main(String[] args){
    List<String> data = Arrays.asList("/foo", "/bar", "/foo/admin", "/foo/cust", "/bar/erp", "/bar/erp/call", "/foo/cust/profile");

    // order by path
    Collections.sort(data, new Comparator<String>(){
        @Override public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    });

    for (String s : data){
        int length = s.split("/").length - 1; // -1 means.. without empty string
        for (int i=0; i< length; i++){
            System.out.print("-- ");
        }
        System.out.println(s);
    }
}   
}

// result is

-- /bar
-- -- /bar/erp
-- -- -- /bar/erp/call
-- /foo
-- -- /foo/admin
-- -- /foo/cust
-- -- -- /foo/cust/profile
like image 44
blueiur Avatar answered Sep 24 '22 04:09

blueiur