思路:
使用Strream.generate方法
代碼實(shí)現(xiàn)IntSupplier,而不是用Lambda表達(dá)式,是為了在get方法外定義共有變量用于存儲(chǔ)已有質(zhì)數(shù)列表。
當(dāng)調(diào)用forEach進(jìn)行流運(yùn)算時(shí),底層是不斷調(diào)用primeSupplier的getAsInt()方法,在每調(diào)用一次就生成一個(gè)新質(zhì)數(shù),并且加到質(zhì)數(shù)列表變量中。
如果直接使用Lambda表達(dá)式,那() -> {} ,括號(hào)內(nèi)部是getAsInt()的方法實(shí)現(xiàn),無(wú)法在內(nèi)部類定義公有變量。那么就只能在外部定義公有變量了,這樣做就不優(yōu)雅了。
// 埃氏篩選法找質(zhì)數(shù)
IntSupplier primeSupplier = new IntSupplier() {
private int currPrime = 2;
private List<Integer> primeList = new ArrayList<>();
@Override
public int getAsInt() {
if(!primeList.isEmpty()){
boolean notFind = true;
while(notFind){
currPrime++;
notFind = primeList.stream().anyMatch(n -> currPrime%n==0);
}
}
primeList.add(currPrime);
return currPrime;
}
};
IntStream.generate(primeSupplier).limit(10).forEach(System.out::println);
運(yùn)行結(jié)果:
2
3
5
7
11
13
17
19
23
29