Search code examples
javacsvprintstream

Java Print Stream printing spaces


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.


Solution

  • 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.