Varargs in Java allow you to pass the final argument to a method as an array or as a sequence of arguments, by placing three periods after the final parameter’s type. This post will list out a few examples of varargs in Java.

1. Collection factory methods (Java 9 and above)

Java 9 provides 12 overloaded versions of List.of() and Set.of() methods, each taking a sequence of arguments. This includes a varargs version that is invoked when the number of arguments exceeds 10.

static <E> List<E> of()
static <E> List<E> of(E e1)1
static <E> List<E> of(E e1, E e2)
……
static <E> List<E> of(E e1, E e2, E e3, E e4 … … E e8, E e9)
static <E> List<E> of(E e1, E e2, E e3, E e4 … … E e8, E e9, E e10)
static <E> List<E> of(E… elements)
 
 
static <E> Set<E> of()
static <E> Set<E> of(E e1)1
static <E> Set<E> of(E e1, E e2)
……
static <E> Set<E> of(E e1, E e2, E e3, E e4 … … E e8, E e9)
static <E> Set<E> of(E e1, E e2, E e3, E e4 … … E e8, E e9, E e10)
static <E> Set<E> of(E… elements)

The following code example demonstrates the varargs version of List.of() method that can handle any number of elements.

Download  Run Code

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

2. Stream.of() method

We can pass an array to the Stream.of() method, which takes varargs.

Download  Run Code

Output:

[1, 2, 3, 4, 5]

3. Guava

Third-party libraries like Guava also provides varargs version of several methods. Guava provides 7 overloaded versions of ImmutableList.of() and ImmutableSet.of() methods, each taking a sequence of arguments and return the corresponding immutable collection. This includes a varargs version for handling any number of elements, as shown below:

static <E> ImmutableList<E> of()
static <E> ImmutableList<E> of(E element)
static <E> ImmutableList<E> of(E e1, E e2)
static <E> ImmutableList<E> of(E e1, E e2, E e3)
static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4)
static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5)
static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E… others)
 
 
static <E> ImmutableSet<E> of()
static <E> ImmutableSet<E> of(E element)
static <E> ImmutableSet<E> of(E e1, E e2)
static <E> ImmutableSet<E> of(E e1, E e2, E e3)
static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4)
static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5)
static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E… others)

The following code example demonstrates the varargs version of ImmutableList.of() method.

Download Code

Output:

[1, 2, 3, 4, 5, 6, 7]

That’s all about varargs examples in Java.