I need some help with java comparator. I need to compare strings by the number of words they contain.
For exampl开发者_Python百科e, "hello" comes before "I see" which comes before "I see you".
Anyone got any ideas how I would do this? Thank you in advance for any help you could give.
import java.util.Comparator;
import java.util.StringTokenizer;
public class WordCountComparator implements Comparator<String> {
public int compare(String str1, String str2) {
if (str1 == str2 || (str1 == null && str2 == null)) {
return 0;
} else if (str1 == null) {
return -1;
} else if (str2 == null) {
return 1;
}
int len1 = new StringTokenizer(str1, " \t\r\n").countTokens();
int len2 = new StringTokenizer(str2, " \t\r\n").countTokens();
return len1 < len2 ? -1 : len1 == len2 ? 0 : 1;
}
}
Write a comparator for a String type. In the compareTo method, simply call string.split(" ") to break it down to 'words' (if that's sufficient), then return the comparison between those two integers.
string.split(" ")
will return an array, where each element is a word. So comparing the number of elements in the array would give you a rough implementation of this. Obviously you may need to handle line-breaks, tabs etc., so keep that in mind.
Apache commons also has some useful methods to do this.
public class StringComparator implements Comparator<String> {
public int compare(String o1, String o2) {
if(o1==null && o2 ==null)
return 0;
String[] bo1 = o1.split("\\s");
String[] bo2 = o2.split("\\s");
return bo1.length >= bo2.length ? bo1.length > bo2.length ? 1 : 0 : -1;
}
}
精彩评论