开发者

Java: Apply Callback to Array Values

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', $ar开发者_运维知识库ray);

Is there a simple way to accomplish this in Java?


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


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();
 }


You could use reflection:

String[] map(java.lang.reflect.Method method, String[] array) {
  String[] new_array = new String[array.length];
  for (int i = 0; i < array.length; i++) new_array[i] = (String)method.invoke(null, new Object[]{array[i]});
  return new_array;
}

Then you just need to declare a static method somewhere and get a reference to it using the reflection API.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜