There's a big difference being lonely and being alone in Walden. Thoreau believes that the vast majority of people out there feel terribly lonely, even in the midst of crowded cities. Paradoxically, we are most alone in a crowd because we lose the company of, well, ourselves, which is what otherwise makes us unique. Without a sense of ourselves, we can't form authentic attachments with others. We can't be good friends. We just become part of the miserable herd. This is probably something we can all relate to: you have to love yourself in order to love others, right? Thoreau's life alone by Walden Pond is an attempt to recover a more authentic sense of who he is. He's alone, an independent spirit, but he's no hermit. Walden isn't a lonely book. It's filled with characters, and more than a few conversations end in robust laughter with good company. What's important, though, is that with a strong sense of self, Thoreau is able to be a part of that company.
Thoreau is right; only when you are alone can you understand who you really are.
Thoreau doesn't prefer solitude to company. Instead, what he most prefers is the company of true friends that share his interests and values.