Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Apply Callback to Array Values

Tags:

java

I'm looking for a simple way to apply a callback method to each element in a String array. For instance in PHP I can make all elements in an array like this:

$array = array_map('strtolower', $array);

Is there a simple way to accomplish this in Java?

like image 223
mellowsoon Avatar asked Oct 26 '10 22:10

mellowsoon


2 Answers

First, object arrays in Java are vastly inferior to Lists, so you should really use them instead if possible. You can create a view of a String[] as a List<String> using Arrays.asList.

Second, Java doesn't have lambda expressions or method references yet, so there's no pretty way to do this... and referencing a method by its name as a String is highly error prone and not a good idea.

That said, Guava provides some basic functional elements that will allow you to do what you want:

public static final Function<String, String> TO_LOWER = 
    new Function<String, String>() {
      public String apply(String input) {
        return input.toLowerCase();
      }
    };

// returns a view of the input list with each string in all lower case
public static List<String> toLower(List<String> strings) {
  // transform in Guava is the functional "map" operation
  return Lists.transform(strings, TO_LOWER);
}

Unlike creating a new array or List and copying the lowercase version of every String into it, this does not iterate the elements of the original List when created and requires very little memory.

With Java 8, lambda expressions and method references should finally be added to Java along with extension methods for higher-order functions like map, making this far easier (something like this):

List<String> lowerCaseStrings = strings.map(String#toLowerCase);
like image 198
ColinD Avatar answered Sep 25 '22 01:09

ColinD


There's no one-liner using built-in functionality, but you can certainly match functionality by iterating over your array:

 String[] arr = new String[...];

 ...

 for(int i = 0; i < arr.length; i++){
     arr[i] = arr[i].toLowerCase();
 }
like image 27
Mark Elliot Avatar answered Sep 23 '22 01:09

Mark Elliot