简体   繁体   中英

Using java streams to find if a number is prime or not

I am reading Cracking the Coding Interview and it has an example of finding prime number which I ran on JShell

boolean isPrime(int n) {
  for (int i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      return false;
    }
  }
  return true;
}

then I am trying to convert this to streams in java, but finding this difficult as mentioned

boolean isPrimeStream(int n) {
  return IntStream.range(0, n) // how to do similar to for loop above
    .anyMatch(i -> n % i == 0);  // i think this is the reason for failure
}

I am reading Cracking the Coding Interview and it has an example of finding prime number which I ran on JShell

boolean isPrime(int n) {
  for (int i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      return false;
    }
  }
  return true;
}

then I am trying to convert this to streams in java, but finding this difficult as mentioned

boolean isPrimeStream(int n) {
  return IntStream.range(0, n) // how to do similar to for loop above
    .anyMatch(i -> n % i == 0);  // i think this is the reason for failure
}

I am reading Cracking the Coding Interview and it has an example of finding prime number which I ran on JShell

boolean isPrime(int n) {
  for (int i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      return false;
    }
  }
  return true;
}

then I am trying to convert this to streams in java, but finding this difficult as mentioned

boolean isPrimeStream(int n) {
  return IntStream.range(0, n) // how to do similar to for loop above
    .anyMatch(i -> n % i == 0);  // i think this is the reason for failure
}

I am reading Cracking the Coding Interview and it has an example of finding prime number which I ran on JShell

boolean isPrime(int n) {
  for (int i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      return false;
    }
  }
  return true;
}

then I am trying to convert this to streams in java, but finding this difficult as mentioned

boolean isPrimeStream(int n) {
  return IntStream.range(0, n) // how to do similar to for loop above
    .anyMatch(i -> n % i == 0);  // i think this is the reason for failure
}
package Java8Practice;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class PrintPrimeNumbers {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    List<Integer> primes = list.stream().filter(n -> isPrime(n)).collect(Collectors.toList());
    System.out.println(primes);
}

static boolean isPrime(int n) {
    return IntStream.range(2, n).noneMatch(i -> n % i == 0);
 }
}

/*Output 
[1, 2, 3, 5, 7]
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM