How to get values of an array in the alphabetical order?
I have an array of strings plus one additional string. I want to use this string and values of array to get a set of string. Then I want to order the set of string alphabetically and extract the string which is the first in the list. Wh开发者_StackOverflow社区at is the easiest way to do it in Java?
ADDED:
I wanted to do it this way:
List<String> playersList = Arrays.asList(players);
playersList.add(userName); // <---------- HERE IS A PROBLEM
Collections.sort(playersList);
I do not get any errors during the compilation. But during the execution I get a "UnsopportedOperationException". And it happens in the second line.
Arrays.asList
wraps the array with an unmodifiable List
, so when you try to add to it it throws UnsupportedOperationException
. What you could do it create a new a ArrayList
and add your elements to it, then you're free to modify it afterwards.
List<String> list = new ArrayList<String>(Arrays.asList(players));
list.add(userName);
If you just want to get the minimum of an array of String
with an additional external element, then you don't have to sort and extract first (which would be O(N log N)
). You can do it in O(N)
.
String minPlayer = Collections.min(Arrays.asList(players));
minPlayer = Collections.min(Arrays.asList(minPlayer, extraPlayer));
Either append the value to the array and sort it with Arrays.sort or create a List of the items and sort them using Collections.sort. The natural ordering of the strings will be alphabetical.
精彩评论