views:

75

answers:

3

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

+1  A: 

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.

Jeff Storey
Do you know if Array.sort() generate a new array or it modifies the input array?
Roman
modifies the original but you could always pass a copy of it (or make a method that wraps Arrays.sort and makes a copy and returns that). Note is Arrays.sort not Array.sort
Jeff Storey
Thanks. I understood how to sort. But I cannot add a value to an array. First i tried `myArra[myArray.length] = newValue`. It did not work (index out of range). Now I am trying to use push. But compiler cannot find method push...
Roman
Right, there is no "push" method. Apache commons provides an easy way to do this http://commons.apache.org/lang/api-release/org/apache/commons/lang/ArrayUtils.html. Or you can just create a new array of your original size+1, copy the original array into it and then set the last element to the element you want to add.
Jeff Storey
I already started to use list. Now I have a list with all elements I need and now I try to sort it. I try to find out how to use `Collections.sort`.
Roman
I have managed to sort a list (I needed to import some stuff). Now i try to find out how to get a first element from a list.
Roman
+1  A: 

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));  
polygenelubricants
+2  A: 

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);
Steve Kuo