digitalinnovationone / ganhando_produtividade_com_Stream_API_Java

Este repositório contém o código-fonte do curso "Ganhando Produtividade com Stream API Java". O curso foi projetado para ajudar desenvolvedores Java a aproveitar ao máximo a poderosa Stream API introduzida no Java 8.
https://web.dio.me/course/ganhando-produtividade-com-stream-api
558 stars 344 forks source link

Desafio 14 e 17 #10

Open jjgirotto opened 9 months ago

jjgirotto commented 9 months ago

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 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

andersoncpdq commented 9 months ago

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. =)

cami-la commented 9 months ago

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. (:

williamlimasilva commented 1 month ago

Caso alguém tenha duvidas no desafio 17 resolvi desse jeito public static void main(String[] args) { List 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 commented 1 month ago

Quem tiver dificuldade para o Desafio 14 public static void main(String[] args) { List 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")); }