使用例子

2020-10-17  本文已影响0人  盗生一
package com.gxhj.frameuse.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Test {

    public static void main(String[] args) {
        HashMap<String, String> mapHoppies = new HashMap<>();
        mapHoppies.put("zs", "本人");
        Student student1 = new Student(1,"张帅1",11,3451.12, Arrays.asList("打篮球","打羽毛球"),mapHoppies);
        Student student2 = new Student(2,"张帅2",12,3452.12, Arrays.asList("打篮球","打羽毛球"),mapHoppies);
        Student student3 = new Student(3,"张帅3",13,3452.12, Arrays.asList("打篮球","打羽毛球"),mapHoppies);
        Student student4 = new Student(4,"张帅4",14,3453.12, Arrays.asList("打篮球","打羽毛球"),mapHoppies);
        ArrayList<Student> lstStu = new ArrayList<>();
        lstStu.add(student1);
        lstStu.add(student2);
        lstStu.add(student3);
        lstStu.add(student4);

        // 获取主键
        List<Integer> collect = lstStu.stream().map(Student::getId).collect(Collectors.toList());
        collect.forEach(
                (e)->{
                    System.out.println("e = " + e);
                }
        );
        // lambada使用 语法形式为 () -> {},其中 () 用来描述参数列表,{} 用来描述方法体,-> 为 lambda运算符 ,读作(goes to)
        // map->将一个对象转为另一个对象。
        // filter->过滤掉一部分元素
        // Predicate->类似条件过滤
        // reduce->将所有值合并为一个
        // 过滤出年龄大于12的
        List<Student> colStu = lstStu.stream().filter(e -> e.getAge() > 12).collect(Collectors.toList());
        colStu.forEach(student -> System.out.println("student = " + student));
        // 计算所有薪水综合
        // double allCost = cost.stream().map(x -> x+x*0.05).reduce((sum,x) -> sum + x).get();
        Integer integer = lstStu.stream().map(x -> x.getAge()).reduce((sum, e) -> sum + e).get();
        System.out.println("aDouble = " + integer);
        // predicate: 就是将过滤中的Perdicate提出来
        List<Student> lstStu1 = filterTest(lstStu, x -> x.getAge() > 13);
    }
    public static List<Student> filterTest(List<Student> languages, Predicate<Student> condition) {
        List<Student> lst = languages.stream().filter(x -> condition.test(x)).collect(Collectors.toList());
        return lst;
    }

}

上一篇下一篇

猜你喜欢

热点阅读