0

I need to generate a tree representation of a tabular data source and am having a hard time getting started. The data is a representation of product hierarchies

Input Data

The Tree structure from this input would look like this:

enter image description here

So far I've written a method in Java which reads the text input (TSV) and generates a 2d String array of the values. From here I am unsure how to proceed. The array class doesn't appear to have the methods I will need to define relationships or add nodes to the tree.

Java Code:

public class ImportTSV  {   
// Global VARs
String[][] tsvArray;
List<String> lines; 

public static void main(String[] args) throws IOException{
    ImportTSV tsv = new ImportTSV();
    String [][] tmp = tsv.readTSV();
    tsv.arr2tree(tmp);
}

public String[][] readTSV() throws IOException{
    // Read File to lines object
    lines = Files.readAllLines(Paths.get("Input\\TestData_small.txt"), StandardCharsets.UTF_8);

    // Set Array bounds to # of lines in input source
    tsvArray = new String[lines.size()][];

    System.out.println("-- Full 2D Array --");
    // Build the array from TSV source
    for(int i=0; i<lines.size(); i++){
        tsvArray[i] = lines.get(i).split("\t");
        System.out.println(Arrays.deepToString(tsvArray[i]));
    }       
    return tsvArray;
}

public void arr2tree(String[][] arr){
    String[][] data = arr;
    String[] tmp = null;
    System.out.println(" ");
    System.out.println("-- Converting to Tree --");

    // Need a tree
    TreeMap<String, String> tm = new TreeMap<String, String>();

    // Loop through [][] to define each line
    for(int i=0;i<data.length;i++){
        // Then seperate by record
        for(int j=0;j<data[i].length-1;j++){
            // Set comparison variables
            String s1 = data[i][j];
            String s2 = data[i][j+1];

            // See the comparison
            System.out.println("Parent Check: " + s1);
            System.out.println("Child Check: " + s2);


            // Set the relationship in the tree if it doesnt exist
            if(tm.(s1)!=s2){
                tm.put(s1, s2); 
                System.out.println(tm.toString());
            }


        }           
    }       
}   

}

I'm fairly new to Java and appreciate any help with solving this problem.

1 Answers1

0

For a start, it would probably be wise to implement a Node that you can store the relationships in.

Here is a good example from another question.

public static class Node<T> {
    private T data;
    private Node<T> parent;
    private List<Node<T>> children;
}

In your case you can probably change the type T to String and since you didn't say if parents have fixed number of children a List is also suited for you.

Community
  • 1
  • 1
meritus
  • 68
  • 2
  • 7