Skip to content

Instantly share code, notes, and snippets.

@andreluisdias
Created August 13, 2017 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreluisdias/391e1671308edd7c654ab61f002de962 to your computer and use it in GitHub Desktop.
Save andreluisdias/391e1671308edd7c654ab61f002de962 to your computer and use it in GitHub Desktop.
Unlimited argument function as @FunctionalInterface
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);
}
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