Green Onyeji
Green Onyeji

Reputation: 259

Mapping a word to its synonyms in java application

I am working on a word-synonyms application but am having a challenge. The challenge/question is how do i map a word and its synonyms in my application database?

Upvotes: 1

Views: 4056

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109597

Synonyms are commutative but not transitive.

I cannot find an example, so the following artificial one:

bank
synonym(bank) = money-institute   => synonym(money-institute) = bank
synonym(bank) = place-to-sit      => synonym(money-institute) = bank

place-to-sit:
synonym(place-to-sit) = bank
synonym(place-to-sit) = chair

NOT synonym(chair) = money-institute

This means that you need only a list of pairs without order, and both one is the synonym of the other and vice versa. And more you need not do.

public class SynonymTable {

private Map<Word, Set<Word>> synonymTable = new HashMap<>();

public Set<Word> getSynonyms(Word word) {
    return synonymTable.get(word);
}

public void registerSynonym(Word word, Word... synonymsOfWord) {
    for (Word syn : synonymsOfWord) {
        putSynonymTable(word, syn); // synonym(word) = syn
        putSynonymTable(syn, word); // synonym(syn) = word
    }
}

private void putSynonymTable(Word word, Word synonymOfWord) {
    Set syns = synonymTable.get(word);
    if (syns == null) {
        syns = new TreeSet<Word>();
        synonymTable.put(word, syns);
    }
    syns.add(synonymOfWord);
}
...

Database variant

CREATE TABLE TWord (
    wordId INT AUTO_INCR,
    wordText VARCHAR(80),
    INDEX(wordText),
    PRIMARY KEY(wordId)
);
CREATE TABLE TSynonym (
    wordFk INT NOT NULL,
    synonymFk INT NOT NULL,
    CONSTRAINT FOREIGN KEY (wordFk) REFERENCES TWord(wordId),
    CONSTRAINT FOREIGN KEY (synonymFk) REFERENCES TWord(wordId),
    PRIMARY KEY(wordFk, synonymFk)
);

Upvotes: 1

Arnab Biswas
Arnab Biswas

Reputation: 4595

If your application as simple as described in the question, then as suggested in other answer Map with a Set or list value is sufficient. If you are comfortable with third party libraries, you may check Guava's Multimap. As per the documentation:

A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.

Upvotes: 0

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236104

Use a map, something like this:

Map<String, List<String>> synonyms;

In the above, the key to the map will be the word and the corresponding value will be a list of synonyms.

In terms of databases, create a table with synonym words and a table with words, each word in the synonyms table will hold a foreign key reference to the word. This can be easily mapped to the above data structure.

Upvotes: 1

Related Questions