Efficiently Convert a Common Array Using Guava

I work with Java 7 , and I'm looking in the Guava API for a way to apply a function to an array without having to first convert it to a collection. I am ready to create my own class for this purpose, but I do not want to reinvent the wheel hehe.

So, as a summary (unless you know exactly what I'm talking about), this is what I have found so far that you can do with Guava to apply the function to the array, as I said:

Integer[] someNumbers = new Integer[]{1, 2, 3};
Integer[] returnedNumbers = Collections2.transform(Arrays.asList(someNumbers), squareNumberFunction).toArray(new Integer[0]);

assertThat(returnedNumbers).isEqualTo(new Integer[]{1, 4, 9});//Using AssertJ here

But I would like to do something like this:

Integer[] someNumbers = new Integer[]{1, 2, 3};
Integer[] returnedNumbers = Arrays.transform(someNumbers, squareNumberFunction);

assertThat(returnedNumbers).isEqualTo(new Integer[]{1, 4, 9});

Ideally, the functionality I'm talking about will be type safe .


EDIT

To further clarify the problem:

  • , , , ( , , ).
  • , ( , , ).
  • .
+4
2

, , . , - (, ?).

public static <A, B> B[] transform(Class<B> theReturnedValueType, Function<A, B> functionToApply, A... theValues) {

    B[] transformedValues = (B[]) Array.newInstance(theReturnedValueType, theValues.length);

    for (int i = 0; i < theValues.length; i++) {
        transformedValues[i] = functionToApply.apply(theValues[i]);
    }

    return transformedValues;
}

( ):

Integer[] returnedNumbers = ArrayTransformer.transform(Integer.class, squareNumberFunction, 1, 2, 3);

assertThat(returnedNumbers).isEqualTo(new Integer[]{1, 4, 9});

, vargargs ( , ), .

, , , (, Android), - (java.lang. reflect.newInstance(...)). , , toArray (T []) , ( , ), , , , , ( ).

+4

, , - , , .

, , Arrays.asList (, ) ImmutableList ( ), , . , ( ), / , .

Java - , Java , , , - .

+4

All Articles