abelorosz
abelorosz

Reputation: 161

Sort sentences based on the Nth word

I have to read a file with one sentence on each line.
Then I have to sort these sentences based on the Nth word (I am given a number as an input parameter which represents the place of the sort-by-this word in the sentence).

File reading is done and I have loaded the words in a two-dimensional string array.

for(String line : Files.readAllLines(file))
for(String word : line.trim().split(" "))

How should I sort the sentences?

Upvotes: 0

Views: 200

Answers (1)

Mena
Mena

Reputation: 48434

Use a custom Comparator<String>, to parametrize your sort invocation (invoked on either a Collection or an Array, through the Collections or Arrays utility classes respectively).

  • You will need to have an instance field in your Comparator, that will represent the Nth word's index you base your sorting on, and a setter or constructor to set it
  • In your compare(String s1, String s2) override, you will use that field to check whether both Strings are long enough and have enough actual words (then, also decide what to do if either doesn't qualify)
  • If both Strings qualify, you will pick those words by itemizing them through a Scanner or Pattern, and return the computation of compare on those two words, instead of the whole Strings
  • That will guarantee that given a list of Strings and a word index, all Strings qualifying to have a separable word at that given word index will be compared based on the lexicographical comparison of those words, and a separate logic for those Strings that do not qualify

Upvotes: 2

Related Questions