简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM