Created
August 13, 2017 02:26
-
-
Save andreluisdias/391e1671308edd7c654ab61f002de962 to your computer and use it in GitHub Desktop.
Unlimited argument function as @FunctionalInterface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sample.function.infinite; | |
/** | |
* It's possible too. Example of a 'unlimited argument' Function interface. | |
* But it can cause Potential heap pollution due to varargs parameter element in @see {@link UnlimitedArgumentFunction#apply(Object...)} | |
* | |
* @author Andre Dias | |
* @since 2017-08-12 | |
*/ | |
@FunctionalInterface | |
public interface UnlimitedArgumentFunction<F, R> { | |
public R apply(F ... elements); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sample.function.infinite; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
/** | |
* Example of usage for @see {@link UnlimitedArgumentFunction}. | |
* | |
* @author Andre Dias | |
* @since 2017-08-12 | |
*/ | |
public class UnlimitedArgumentFunctionImpl implements UnlimitedArgumentFunction<Integer, Integer> { | |
/** | |
* Just add elements (simple example). | |
* | |
* @see sample.function.infinite.UnlimitedArgumentFunction#apply(java.lang.Object[]) | |
*/ | |
public Integer apply(final Integer... elements) { | |
Integer result = 0; | |
for (Integer current : elements) { | |
result += current; | |
} | |
return result; | |
} | |
public static void main(String[] args) { | |
List<Integer> fewElements = Arrays.asList(1, 2); | |
List<Integer> someElements = Arrays.asList(1, 2, 3, 4, 5); | |
List<Integer> bigElementList = new ArrayList<Integer>(); | |
for (int i = 0; i < 10000; i++) { | |
bigElementList.add(i); | |
} | |
final UnlimitedArgumentFunction<Integer, Integer> mainFunction = new UnlimitedArgumentFunctionImpl(); | |
System.out.println( | |
String.format("'Few Elements List' add result is: %s", | |
mainFunction.apply( (Integer[])fewElements.toArray() ))) ; | |
System.out.println( | |
String.format("'Some Elements List' add result is: %s", | |
mainFunction.apply( (Integer[])someElements.toArray() ))) ; | |
System.out.println( | |
String.format("'Big Element List' add result is: %s", | |
mainFunction.apply( Arrays.copyOf(bigElementList.toArray(new Integer[] {}), bigElementList.size()) ))) ; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment