Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
Consumer with varargs

Suggest the following:

  Consumer<Object[]> consumer = (args) -> { /* Do something */ }

To make use of the consumer, I have to create an Object array. So, I'd have to write something like

  consumer.accept(new Object[]{ object0, object1, ... });

Obviously, I'd rather have something like

  Consumer<Object...> consumer = (args) -> { /* Do something */ }
  consumer.accept(object0, object1, ...);

Is something like this possible?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

But you can create your own functional interface as follows:


interface IntVarArgsConsumer {
        void accept(int ...s);
}
    
IntVarArgsConsumer printArray = arr-> System.out.println(Arrays.toString(arr));
        
printArray.accept(1,2,3,4,5);
printArray.accept(1,2,3);

prints

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

But I caution you not to mix generic type parameters and varargs. Otherwise you can pollute the heap and get ClassCastExceptions. If you just want to process Strings, then use the String type. If Objects, use the Object type. But not some type R as you might see in other methods.

over 4 years ago · Santiago Trujillo Relatório

0

Variable arity parameter (varargs) is a syntactic element, a special token indicating that a method (or a constructor) expects 0 or more arguments of that type. And these arguments will be wrapped by an array (so that technically they will constitute a single argument) when the method gets executed.

Its usage is limited: a method can have only one parameter of variable arity and it must be defined in the last position.

Variable arity parameter isn't a type by itself. If you'll try to use eclipses ... anywhere apart from the last position of a method (constructor) declaration, you'll get a compile error (take a look at JLS for more information).

In order to use a variable number of arguments in a function, you can define a functional interface with a method of variable arity. And this method is the only place where elipses ... needs to be used.

@FunctionalInterface
public interface MyConsumer<T> {
    void accept(T... items);
}
MyConsumer<String> myConsumer = items -> Stream.of(items).forEach(System.out::println);

myConsumer.accept("A", "B", "C");

Will give an output:

A
B
C
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda