Skip to content

Desafio 7 #22

Open
Open

Description

@raulward

Existe alguma inconsistência ou má prática em fazer dessa forma?

Além disso, existe alguma maneira mais eficiente de fazer a busca do elemento?

public class Desafio7 {
    public static void main(String[] args) {
        List<Integer> numeros = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 4, 3);
        int maiorNumero = numeros.stream()
                .max(Comparator.naturalOrder())
                .orElseThrow(() -> new NoSuchElementException("Nao foi possivel achar o elemento"));

        int segundoMaiorNumero = numeros.stream()
                .filter(n -> n != maiorNumero)
                .max(Comparator.naturalOrder())
                .orElseThrow(() -> new NoSuchElementException("Nao foi possivel achar o elemento"));

        System.out.println(segundoMaiorNumero);
    }
}

Activity

  1. fgmarcal commented on Aug 9, 2024

    @fgmarcal

    bom dia, amigo

    fiz assim:

    //Desafio 7 - Encontrar o segundo número maior da lista:
    public static int findSecondLargest(List<Integer> list) {
        var maxNumber = list.stream().max(Integer::compare).get();
        var secondLargest = list.stream()
                .filter(n -> n < maxNumber)
                .max(Integer::compare).get();
    
        return secondLargest;
    }
    
  2. GustavoSutanaLima commented on Aug 25, 2024

    @GustavoSutanaLima

    Pensei que se você invocasse stream() em uma lista, não era mais possível usar de novo na mesma lista. Estranho... entendi errado

  3. samu-benjamim commented on Jan 8, 2026

    @samu-benjamim

    Boa esse deu trabalho.

    a minha ficou assim:

     public void verificarSegundoMaiorNumeros(List<Integer> list) {
            Optional<Integer> segundoMaiorNum = list.stream()
                    .distinct()
                    .sorted(Comparator.reverseOrder())
                    .limit(2)
                    .skip(1)
                    .peek(System.out::println)
                    .findFirst();
        }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions