Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lowercase every element of a collection efficiently?

Tags:

java

string

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>(); strings.add("HELLO"); strings.add("WORLD");  for(int i=0,l=strings.size();i<l;++i) {   strings.add(strings.remove(0).toLowerCase()); } 

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>(); strings.apply(   function (element)   { this.replace(element, element.toLowerCase();) }  ); 

Thanks,

like image 970
Chris Avatar asked Apr 15 '10 11:04

Chris


People also ask

How do you make everything in a string lowercase?

lower() Return value lower() method returns the lowercase string from the given string. It converts all uppercase characters to lowercase. If no uppercase characters exist, it returns the original string.

How do you make all elements in a lowercase list?

Use the str. lower() Function and a for Loop to Convert a List of Strings to Lowercase in Python. The str. lower() method is utilized to simply convert all uppercase characters in a given string into lowercase characters and provide the result.

How do I lowercase everything in JavaScript?

JavaScript String toLowerCase() The toLowerCase() method converts a string to lowercase letters. The toLowerCase() method does not change the original string.

Which method is used to lowercase all the characters in a string?

The toLowerCase() method converts a string to lower case letters.


1 Answers

Yet another solution, but with Java 8 and above:

List<String> result = strings.stream()                              .map(String::toLowerCase)                              .collect(Collectors.toList()); 
like image 185
Igor G. Avatar answered Oct 10 '22 02:10

Igor G.