Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class WordUtil {
- List<Word> words;
- /**
- * Parse a sentence to obtain the unique words and the number of occurrences, and then pass each to the supplied
- * WordCountConsumer.
- *
- * @param value A sentence.
- * @return A list of Words with their count.
- */
- public void parse(String value, WordCountConsumer consumer) {
- words = new ArrayList<>();
- String[] values = value.split(" ");
- for (int i = 0; i < values.length; i++) {
- Word word = new Word(values[i], 1);
- if (words.contains(word)) {
- Word tmpWord = words.get(words.indexOf(word));
- tmpWord.setCount(tmpWord.getCount() + 1);
- } else {
- words.add(word);
- }
- }
- for (Word word : words) {
- consumer.consume(word.getValue(), word.getCount());
- }
- }
- public static void main(String[] args) {
- String test = "First half goals for Chelsea, Fulham and Leeds. Second half goals for Chelsea and Fulham.";
- WordUtil wu = new WordUtil();
- wu.parse(test, (word, count) -> System.out.println(word + " occurred " + count + " times"));
- }
- }
- public class Word {
- String value;
- int count;
- public Word(String value, int count) {
- super();
- this.value = value;
- this.count = count;
- }
- public String getValue() {
- return value;
- }
- public void setValue(String value) {
- this.value = value;
- }
- public int getCount() {
- return count;
- }
- @Override
- public String toString() {
- return "Word [value=" + value + ", count=" + count + "]";
- }
- public void setCount(int count) {
- this.count = count;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- Word other = (Word) obj;
- if (count != other.count) {
- return false;
- }
- if (value == null) {
- if (other.value != null) {
- return false;
- }
- } else if (!value.equals(other.value)) {
- return false;
- }
- return true;
- }
- }
- public interface WordCountConsumer {
- void consume(String word, int occurences);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement