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

134
Visualizações
Create a List of random Integers using Stream and sum all elements except the smallest?

I want to generate 4 random numbers, ranging from 1 through 6 inclusive. Then I want to get the sum of these elements excluding the smallest value.

I am currently creating one stream to populate a list:

List<Integer> values =  r.ints(4,1,7).boxed().collect(Collectors.toList())

Then I remove the smallest value and use another stream to get the sum of the values:

values.stream().mapToInt(Integer::intValue).sum();

Can someone suggest a way to perform all these operations in a single stream?

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

0

Sort the stream, then skip the first (ie smallest) element:

int sumExceptSmallest = IntStream.of(4,1,7).sorted().skip(1).sum(); // 11

or in your specific case:

int sumExceptSmallest = r.ints(4,1,7).sorted().skip(1).sum();

Note that while this may be the coolest and most efficient for the coder, it is not the most efficient possible solution because the sort has time complexity of O(n log n). The most efficient run time would be a single pass to both find the smallest and compute the sum, then subtract one from the other, yielding the solution in O(n) time.

over 4 years ago · Santiago Trujillo Relatório

0

Using IntSummaryStatistics can calculate this in your stream with a single pass:

IntStream stream = /* random stream of integers */;
IntSummaryStatistics stats = stream.summaryStatistics();
int sum = stats.sum();
sum -= stats.min(); //sum, minus the lowest element
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