Java8新特性——lambda表达式.(案例:完全数分类)

需求:输入一个数,判断其类型(完全数,过剩数,不足数)

完全数:自身之外所有因数和==自身

过剩数:自身之外所有因数和>自身

不足数:自身之外所有因数和<自身

 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 }

测试类:

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 }

 

posted @ 2017-06-24 01:09  Tomas曼  Views(669)  Comments(0Edit  收藏  举报