[英]Using java streams to find if a number is prime or not
我正在阅读Cracking the Coding Interview ,它有一个找到我在JShell上运行的素数的例子
boolean isPrime(int n) {
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
然后我正在尝试将其转换为java中的流,但如前所述发现这很困难
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
}
我正在阅读《破解编码面试》 ,其中有一个示例,它找到了我在JShell上运行的素数
boolean isPrime(int n) {
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
然后我试图将其转换为java中的流,但是发现这很难提到
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
}
我正在阅读《破解编码面试》 ,其中有一个示例,它找到了我在JShell上运行的素数
boolean isPrime(int n) {
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
然后我试图将其转换为java中的流,但是发现这很难提到
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
}
我正在阅读《破解编码面试》 ,其中有一个示例,它找到了我在JShell上运行的素数
boolean isPrime(int n) {
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
然后我试图将其转换为java中的流,但是发现这很难提到
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]
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.