Sorting a list of strings based on number of words

1k Views Asked by At

I have a file that dumps every line into a position in an ArrayList and I want the user to be able to sort the list to only having lines that have a certain number of words. I can't figure out how to make it print the remaining list (of correct numbered entries).

It starts by finding the first word in the list then it iterates through the CharSequence and checks if the character is equal to a space, ' ' If it is, then it increments nWords by 1 and if nWords is not equal to userInput(the number the user inputs to sort the list by number of words), it should remove that item from the list.

ArrayList<CharSequence> str = new ArrayList();
str.add("Hello");
str.add("Hi there");
str.add("toad");
str.add("i see you");

System.out.println("How many words?");
Scanner scan = new Scanner(System.in);
int userInput = scan.nextInt();

for (int loopNumber = 0; loopNumber < str.size(); ) {
    int nWords = 1;
    for (int i = 0; i < str.get(loopNumber).length(); i++) {
        if ( str.get(loopNumber).charAt(i) == ' ') {
            nWords++;
            if (nWords != userInput) {
                str.remove(loopNumber);
            }
        }
    }
    loopNumber++;
}
3

There are 3 best solutions below

0
On

Try something like this ..... (the compare method might not be the most efficient one!)

ArrayList<String> str = new ArrayList<String>();
    str.add("Hello");
    str.add("Hi there");
    str.add("toad");
    str.add("i see you");

    Comparator<String> stringComparator = new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            String [] words1 = null;
            String [] words2 = null;
            try {
                words1 = o1.split(" ");
                words2 = o2.split(" ");
            } catch (Exception e) {
                //ignore
            }

            if (words1 != null && words2 != null) {
                if (words1.length > words2.length) {
                    return 1;
                } else if (words1.length == words2.length) {
                    return 0;
                } else {
                    return -1;
                }
            } else if (words1 != null) {
                return 1;
            } else {
                return -1;
            }
        }
    };

    Collections.sort(str, stringComparator);
0
On

You can use the Comparator interface. Check below example

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortedList {
 public static void main(String[] args) {
  ArrayList<SimpleString> strArray = new ArrayList<SimpleString>();
  strArray.add(new SimpleString("String"));
  strArray.add(new SimpleString("abc"));
  strArray.add(new SimpleString("Test String"));

  Collections.sort(strArray, new SimpleString(""));

  for (SimpleString str : strArray) {
   System.out.println(str.getTestString());
  }
 }
}

class SimpleString implements Comparator<SimpleString> {
 String testString;

 public SimpleString(String testString) {
  this.testString = testString;
 }

 public String getTestString() {
  return testString;
 }

 public void setTestString(String testString) {
  this.testString = testString;
 }

 @Override
 public int compare(SimpleString o1, SimpleString o2) {
  // TODO Auto-generated method stub
  int strLength = o1.getTestString().length()
    - o2.getTestString().length();
  return strLength;
 }
}

0
On

You don't need to sort. You need to remove those lines without the correct number of words.

for this task, an Iterator is the weapon of choice, because you can call its remove() method while iterating:

for (Iterator<String> i = str.iterator(); i.hasNext();) {
    if (i.next().split(" +").length != userInput)
        i.remove();
}

That's all there is to it.

Also note the considerably more succinct way of counting words via the split() method.