Java8新特性——lambda表達式.(案例:徹底數分類)

需求:輸入一個數,判斷其類型(徹底數,過剩數,不足數)java

徹底數:自身以外全部因數和==自身測試

過剩數:自身以外全部因數和>自身spa

不足數:自身以外全部因數和<自身code

 1 package cn._3.numberclassifier;
 2 
 3 //BEGIN number_classifier_java8
 4 import java.util.List;
 5 import java.util.stream.IntStream;
 6 
 7 import static java.lang.Math.sqrt;
 8 import static java.util.stream.Collectors.toList;
 9 import static java.util.stream.IntStream.range;
10 
11 public class NumberClassifier {
12 
13     // BEGIN java8_filter
14     public static IntStream factorsOf(int number) {
15         return range(1, number + 1).filter(potential -> number % potential == 0);
16     }
17     // END java8_filter
18     public static int aliquotSum(int number) {
19         return factorsOf(number).sum() - number;
20     }
21     public static boolean isPerfect(int number) {
22         return aliquotSum(number) == number;
23     }
24     public static boolean isAbundant(int number) {
25         return aliquotSum(number) > number;
26     }
27     public static boolean isDeficient(int number) {
28         return aliquotSum(number) < number;
29     }
30     // END number_classifier_java8
31 
32     // BEGIN java8_filter_fast
33     public static List<Integer> fastFactorsOf(int number) {
34         List<Integer> factors = range(1, (int) (sqrt(number) + 1))
35                 .filter(potential -> number % potential == 0).boxed()// 返回stream<Integer>
36                 .collect(toList());// 摺疊/化約,reduce
37         List<Integer> factorsAboveSqrt = factors.stream().map(e -> number / e).collect(toList());
38         factors.addAll(factorsAboveSqrt);
39         //將stream變爲ArrayList
40         return factors.stream().distinct().collect(toList());
41     }
42     // END java8_filter_fast
43 }

測試類:blog

1 package cn._3.numberclassifier;
2 
3 public class Mmain {
4 
5     public static void main(String[] args) {
6         Integer number = 666;
7         System.out.println(NumberClassifier.isPerfect(number)+","+NumberClassifier.isAbundant(number)+","+NumberClassifier.isDeficient(number));
8     }
9 }
相關文章
相關標籤/搜索