Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform a Generic Array Efficiently Using Guava

I'm working with Java 7, and I'm searching in the Guava API for a way to apply a function to an array without having to convert it to a Collection first. I'm willing to create my own class for such purpose, but I don't want to reinvent the wheel hehe.

So as a summary (in case you don't know exactly what I'm talking about), this is what I've found so far that you can do with Guava in order to apply a function to an 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 be able to do something like this instead:

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 would be type-safe.


EDIT

For even further clarification of the problem:

  • The arrays I'm talking about are not primitive arrays, they reference complex objects (I only used integers to easily exemplify what I was talking about).
  • I have no control over the received or send structures, they are arrays (imagine a legacy code situation where that's possible if you think that helps you understand the problem better).
  • Efficiency is a must when transforming the arrays and accessing them.
like image 938
Rodrigo Quesada Avatar asked Jan 10 '23 09:01

Rodrigo Quesada


1 Answers

It's not true that arrays are considerably faster than collections - some collections are just wrappers over arrays so you loose nothing but gets the best of both worlds.

Coming back to your case I think you can use Arrays.asList (a list backed by your array) or ImmutableList (if you don't need growing array) whatever suits you but don't use Arrays. The very first sign is that you have to write unnecessary code (your answer and more in future) which you'll have to maintain/tune in future, in my experience it's not worth it.

Java is a higher level language and such tiny optimizations should be better left to Java for all the good reasons but even after all this if you still have doubts I would suggest you to write a micro benchmark to validate your assumption.

like image 93
Premraj Avatar answered Jan 19 '23 02:01

Premraj