java8,让代码更优雅

使用lambda表达式和方法引用改进了一下代码,看起来舒服多了

package com.itheima.base.test.lambda;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class PredicateTest {
    public static void main(String[] args) {
        List languages = Arrays.asList("Java","Python","C++","Php","Scala");
        System.out.println("language which start with \"J\" :");
        //filter(languages, str -> str.toString().startsWith("J")).forEach(s -> System.out.println(s));
        /*
         * 下面一行代码相对上一行代码改进了两个点:
         * 1.Predicate使用了泛型,toString()方法不再需要
         * 2.方法引用简化代码
         */
        filter(languages, str -> str.startsWith("J")).forEach(System.out::println);
        System.out.println("language which end with \"a\" : ");
        filter1(languages,str->str.endsWith("a")).forEach(System.out::println);
    }
    private static List filter(List names, Predicate condition){
        List filteredNames = new ArrayList<>();
        for (String name : names) {
            if(condition.test(name)){
                filteredNames.add(name);
            }
        }
        return filteredNames;
    }

    private static List filter1(List names,Predicate condition){
        List filteredNames = new ArrayList<>();
       //names.stream().filter(name -> condition.test(name)).forEach(e->filteredNames.add(e));
       //names.stream().filter(condition::test).forEach(filteredNames::add);
       names.stream().filter(condition).forEach(filteredNames::add);
       return filteredNames;
    }
}

 

 

 

你可能感兴趣的:(java8)