在日常开发过程当中,能把代码写出来,不一定就意味着能把代码写好,说不准,所写的代码在他人看来,其实就是一坨乱七八糟的翔,因此,代码简化尤其重要,我曾经遇到过这样一个类型的代码,即if-else里都有相同的for循环,这时,我就思考了,如何简化它可以既提高代码性能又减少代码量。
1 public static void main(String[] args) {
2 String status = "is";
3 String[] arrayStr = {"1", "3", "4", "6"};
4 if ("is".equals(status)) {
5 for (int i = 0; i < arrayStr.length; ++i) {
6 System.out.println("执行了正确的方法");
7 }
8 } else {
9 for (int i = 0; i < arrayStr.length; ++i) {
10 System.out.println("执行了错误的方法");
11 }
12
13 }
14 }
研究了一番后,发现jdk1.8有一个Lambda新特性,其实,这玩意很有用,若能熟悉它,可以减少很多的代码量,也能一定提高代码的性能,例如,我通过Lambda表达式将上面的代码简化这了这样,看起来是不是就没那么冗余了:
1 public static void main(String[] args) {
2 String status = "is";
3 String[] arrayStr = {"1", "3", "4", "6"};
4
5 Arrays.asList(arrayStr).stream().forEach(
6 (e) -> {
7 if ("is".equals(status)) {
8 System.out.println("执行了正确的方法");
9 } else {
10 System.out.println("执行了错误的方法");
11 }
12 }
13 );
14 }
网友评论