I have a List<String>
object that contains country names. How can I sort this list alphabetically?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- How to toggle on Order in ReactJS
- StackExchange API - Deserialize Date in JSON Respo
You can create a new sorted copy using Java 8 Stream or Guava:
Another option is to sort in-place via Collections API:
Better late than never! Here is how we can do it(for learning purpose only)-
In one line, using Java 8:
By using
Collections.sort()
, we can sort a list.output:
Here is what you are looking for
Solution with Collections.sort
If you are forced to use that List, or if your program has a structure like
then Thilos answer will be the best way to do it. If you combine it with the advice from Tom Hawtin - tackline, you get:
Solution with a TreeSet
If you are free to decide, and if your application might get more complex, then you might change your code to use a TreeSet instead. This kind of collection sorts your entries just when they are inserted. No need to call sort().
Side note on why I prefer the TreeSet
This has some subtle, but important advantages:
TreeSet<String> countyNames
and instantly knows: this is a sorted collection of Strings without duplicates, and I can be sure that this is true at every moment. So much information in a short declaration.Using the right collection for the right task is a key to write short and bug free code. It's not as demonstrative in this case, because you just save one line. But I've stopped counting how often I see someone using a List when they want to ensure there are no duplictes, and then build that functionality themselves. Or even worse, using two Lists when you really need a Map.
Don't get me wrong: Using Collections.sort is not an error or a flaw. But there are many cases when the TreeSet is much cleaner.