To have efficient many-to-many relation in Java
Posted
by Masi
on Stack Overflow
See other posts from Stack Overflow
or by Masi
Published on 2010-03-10T14:37:34Z
Indexed on
2010/03/12
8:07 UTC
Read the original article
Hit count: 327
How can you make the efficient many-to-many
-relation from fileID
to Words
and from word
to fileIDs
without database -tools like Postgres in Java?
I have the following classes.
The relation from fileID
to words
is cheap, but not the reverse, since I need three for
-loops for it.
My solution is not apparently efficient.
Other options may be to create an extra class that have word
as an ID with the ArrayList
of fileID
s.
Reply to JacobM's answer
The relevant part of MyFile's constructors is:
/**
* Synopsis of data in wordToWordConutInFile.txt:
* fileID|wordID|wordCount
*
* Synopsis of the data in the file wordToWordID.txt:
* word|wordID
**/
/**
* Getting words by getting first wordIDs from wordToWordCountInFile.txt and then words in wordToWordID.txt.
*/
InputStream in2 = new FileInputStream("/home/dev/wordToWordCountInFile.txt");
BufferedReader fi2 = new BufferedReader(new InputStreamReader(in2));
ArrayList<Integer> wordIDs = new ArrayList<Integer>();
String line = null;
while ((line = fi2.readLine()) != null) {
if ((new Integer(line.split("|")[0]) == currentFileID)) {
wordIDs.add(new Integer(line.split("|")[6]));
}
}
in2.close();
// Getting now the words by wordIDs.
InputStream in3 = new FileInputStream("/home/dev/wordToWordID.txt");
BufferedReader fi3 = new BufferedReader(new InputStreamReader(in3));
line = null;
while ((line = fi3.readLine()) != null) {
for (Integer wordID : wordIDs) {
if (wordID == (new Integer(line.split("|")[1]))) {
this.words.add(new Word(new String(line.split("|")[0]), fileID));
break;
}
}
}
in3.close();
this.words.addAll(words);
The constructor of Word is at the paste.
© Stack Overflow or respective owner