1

I'm trying to print out a collection of words to a CSV file and am trying to avoid spaces being printed as a word.

    static TreeMap<String,Integer> wordHash = new TreeMap<String,Integer>();
    Set words=wordHash.entrySet();
    Iterator it = words.iterator();

      while(it.hasNext()) {
        Map.Entry me = (Map.Entry)it.next();
        System.out.println(me.getKey() + " occured " + me.getValue() + " times");
        if (!me.getKey().equals(" ")) {
        ps.println(me.getKey() + "," + me.getValue());
        }
    }

Whenever I open the CSV, as well as in the console, the output is :

        1
  10    1
   a    4
test    2

I am trying to remove that top entry of a space, I thought the statement checking if the key wasn't a space would work however it's still printing spaces. Any help is appreciated. Thanks.

CS2016
  • 331
  • 1
  • 3
  • 15
  • try `String#trim()` on your key and value – Sanjeev May 04 '16 at 05:57
  • We can't know what it is. It could be two spaces, three spaces, a tab, a non-breaking space, etc. Use your debugger and see by yourself. Or open the file with a text editor and see by yourself. – JB Nizet May 04 '16 at 05:57

1 Answers1

0

Your condition will eliminate only single space keys. If you want to eliminate any number of empty spaces, use :

if (!me.getKey().trim().isEmpty()) {
    ...
}

This is assuming me.getKey() can't be null.

Eran
  • 387,369
  • 54
  • 702
  • 768