Reputation: 161
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
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).
Comparator
, that will represent the Nth
word's index you base your sorting on, and a setter or constructor to set itcompare(String s1, String s2)
override, you will use that field to check whether both String
s are long enough and have enough actual words (then, also decide what to do if either doesn't qualify)String
s 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 String
sString
s and a word index, all String
s 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 String
s that do not qualifyUpvotes: 2