0

I am new to java and trying to figure out how to combine several treemaps into a table.

I have a java program that reads a text file and creates a treemap indexing the words in the file. The output has individual words as the key and the list of pages it appears on as the value. an example looks like this:

a 1:4:7
b 1:7
d 2

Now my program currently creates a thread for several text files and creates Treemaps for each file. I would like to combine these treemaps into one output. So say we have a second text file that looks like this:

a 1:2:4
b 3
c 7

The final output I am trying to create is a csv table that looks like this:

key,file1,file2
a,1:4:7,1:2:4
b,1:7,3
c,,7
d,2,

Is there a method to combine maps like this? I am a sql developer primarily so my idea was to print each map to a txt file along with the file name and then pivot this list based on the file name. This didn't seem like a very java like way to approach the problem though.

1 Answer 1

1

I think you need to do it manually.

I didnt compile my solution and it didnt write to csv file, but it should give you hint:

public void writeCsv(List<MyTreeMap> list) {
    Set<String> ids = new TreeSet<String>();

    // ids will store all unique key in your example: a,b,c,d
    for(MyTreeMap m:list) {
        for(String id:m.keySet()) {
            ids.insert(id);
        }
    }

    // iterate ids [a,b,c,d] 
    for(String id:ids) {
        StringBuffer line = new StringBuffer();
        line.append(id);
        for(MyTreeMap m:list) {
            String pages = m.get(id);
            // pages will contains "1:4:7" like your example.
            line.append(",");
            line.append(pages);
        }
        System.out.println(line);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.