Chris Chris - 1 year ago 81
Java Question

How to lowercase every element of a collection efficiently?

What's the most efficient way to lower case every element of a List or Set?

My idea for a List:

final List<String> strings = new ArrayList<String>();

for(int i=0,l=strings.size();i<l;++i)

Is there a better, faster way? How would this example look like for a Set? As there is currently no method for applying an operation to each element of a Set (or List) can it be done without creating an additional temporary Set?

Something like this would be nice:

Set<String> strings = new HashSet<String>();
function (element)
{ this.replace(element, element.toLowerCase();) }


Answer Source

This seems like a fairly clean solution for lists. It should allow for the particular List implementation being used to provide an implementation that is optimal for both the traversal of the list--in linear time--and the replacing of the string--in constant time.

public static void replace(List<String> strings)
    ListIterator<String> iterator = strings.listIterator();
    while (iterator.hasNext())

This is the best that I can come up with for sets. As others have said, the operation cannot be performed in-place in the set for a number of reasons. The lower-case string may need to be placed in a different location in the set than the string it is replacing. Moreover, the lower-case string may not be added to the set at all if it is identical to another lower-case string that has already been added (e.g., "HELLO" and "Hello" will both yield "hello", which will only be added to the set once).

public static void replace(Set<String> strings)
    String[] stringsArray = strings.toArray(new String[0]);
    for (int i=0; i<stringsArray.length; ++i)
        stringsArray[i] = stringsArray[i].toLowerCase();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download