代码改变世界

17_8_15 lambda 表达式

2017-08-15 09:03  小歪1991  阅读(138)  评论(0编辑  收藏  举报

1. ->

e.g.:表达式person -> person.getAge(); 传入参数是person-----Person类的一个实例,返回值是person.getAge()
        传入的参数   ->   对参数进行操作     +   返回值
 

2. ::

双冒号运算就是Java中的:[方法引用]
格式是:类名::方法名
注意是方法名哦,后面没有括号“()”哒。为啥不要括号,因为这样的是式子并不代表一定会调用这个方法。这种式子一般是用作Lambda表达式,Lambda有所谓懒加载嘛,不要括号就是说,看情况调用方法

3 打印list

 //--集合
        List<Integer>  list = Arrays.asList(1,2,3,4,5,6,7);
        //遍历集合--普通方式
        for(int i=0;i<list.size();i++){
            System.out.print(list.get(i));
        }
        System.out.print("----------");

        for (Integer in:list) {
            System.out.print(in);
        }
        System.out.print("----------");

        //lambda
        list.forEach(in-> System.out.print(in));
        //lambda
        list.forEach(System.ot::print());

注意1:

表达式:
person -> person.getAge();
可以替换成
Person::getAge

表达式
() -> new HashMap<>();
可以替换成
HashMap::new

注意2:

把List<String>里面的String全部大写并返还新的ArrayList<String>:
public void convertTest() {  
    List<String> collected = new ArrayList<>();  
    collected.add("alpha");  
    collected.add("beta");  
    collected = collected.stream().map(string -> string.toUpperCase()).collect(Collectors.toList());  
    System.out.println(collected);  
}  

现在也可以被替换成下面的写法:

public void convertTest() {  
    List<String> collected = new ArrayList<>();  
    collected.add("alpha");  
    collected.add("beta");  
    collected = collected.stream().map(String::toUpperCase).collect(Collectors.toCollection(ArrayList::new));//注意发生的变化  
    System.out.println(collected);  
}  

Arrays 转化为 Stream

both Arrays.stream and Stream.of
e.g.:
        String[] array = {"a", "b", "c", "d", "e"};
        //Arrays.stream
        Stream<String> stream1 = Arrays.stream(array);
        stream1.forEach(x -> System.out.println(x));

        //Stream.of
        Stream<String> stream2 = Stream.of(array);
        stream2.forEach(x -> System.out.println(x));

Stream to List

a Stream to a List via Collectors.toList

        Stream<String> language = Stream.of("java", "python", "node");

        //Convert a Stream to List
        List<String> result = language.collect(Collectors.toList());