ganhando_produtividade_com_Stream_API_Java icon indicating copy to clipboard operation
ganhando_produtividade_com_Stream_API_Java copied to clipboard

Desafio 14 e 17

Open jjgirotto opened this issue 2 years ago • 4 comments

Oi Cami, tudo bem? Estou com dificuldade no desafio 14 e 17 por conta dos números primos. Poderia me ajudar com o código por favor? tentei o 14 assim: public class Desafio14 { public static void main(String[] args) { List<Integer> numeros = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 4, 3);

    //Encontre o maior número primo da lista:
    int maiorPrimo = numeros.stream()
        .filter(n -> (n % n == 0 && n % 1 == 0));
        .mapToInt(Integer::intValue)
        .max()
    System.out.println(maiorPrimo);
}

} mas não faz sentido, então não consegui fazer o 17 por ser parecido também

jjgirotto avatar Sep 14 '23 17:09 jjgirotto

Boa noite.

A questão 14 resolvi desta forma:

  Integer maxPrime = numbers.stream().filter(n -> {
      if (n < 2)
          return false;
      for (int i = 2; i < n; i++) {
          if (n % i == 0)
              return false;
      }
      return true;
  }).max(Comparator.naturalOrder()).orElse(null);

Já a questão 17 é bem semelhante:

    numbers.stream().filter(n -> {
        if (n < 2)
            return false;
        for (int i = 2; i < n; i++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }).forEach(System.out::println);

Espero ter ajudado. =)

andersoncpdq avatar Sep 18 '23 01:09 andersoncpdq

Temos várias formas de resolver esses desafios, tá? Segue uma issue que eu respondi, sugerindo uma forma de resolver: https://github.com/digitalinnovationone/ganhando_produtividade_com_Stream_API_Java/issues/11#issuecomment-1733639978

Veja se te ajuda. Qualquer dúvida é só falar. (:

cami-la avatar Sep 25 '23 12:09 cami-la

Caso alguém tenha duvidas no desafio 17 resolvi desse jeito public static void main(String[] args) { List<Integer> numeros = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 4, 3); System.out.print("Numeros primos da lista: "+numeros.stream() .filter(n -> { if (n <= 1) return false; for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) return false; } return true; }) .toList()); }

williamlimasilva avatar May 10 '24 19:05 williamlimasilva

Quem tiver dificuldade para o Desafio 14 public static void main(String[] args) { List<Integer> numeros = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 4, 3); numeros.stream() .filter(n -> { if (n <= 1) return false; for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) return false; } return true; }) .max(Comparator.naturalOrder()) .ifPresentOrElse(n-> System.out.println("Maior numero primo da lista: "+n),()-> System.out.println("Não foi encontrado numeros primos")); }

williamlimasilva avatar May 10 '24 19:05 williamlimasilva