Java教程

java中流操作-stream

本文主要是介绍java中流操作-stream,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

流操作

图片来源于

简单使用

有这样两个对象StudentTeacher

常用的方法(持续更新)

@Slf4j
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class StreamUtilTest {

    public List<Studient> studientList = new ArrayList<>();
    public List<Teacher> teacherList = new ArrayList<>();

    @BeforeAll
    private void bef(){
        Studient studient1 = new Studient("1","张三", 20.2f, "北京", "3001");
        Studient studient2 = new Studient("2","李四", 20.3f, "北京", "3001");
        Studient studient3 = new Studient("3","赵六", 20.6f, "天津", "3001");
        Studient studient4 = new Studient("4","燕南七", 19.0f, "深圳", "3002");
        Studient studient5 = new Studient("5","老八", 21.0f, "杭州", "3002");

        studientList.add(studient1);
        studientList.add(studient2);
        studientList.add(studient3);
        studientList.add(studient4);
        studientList.add(studient5);

        Teacher teacher1 = new Teacher("3001", "刘老师");
        Teacher teacher2 = new Teacher("3002", "李老师");
        teacherList.add(teacher1);
        teacherList.add(teacher2);

    }

    @Test
    void test01(){
        log.info("学生信息是{}", studientList);
    }

    @Test
    void streamTest(){
        // stream 过滤
        List<Studient> studientList1 =  studientList.stream().filter(item -> "3001".equals(item.getTeachId())).collect(Collectors.toList());
        log.info("筛选出导师id是 3001 的学生 {}", studientList1);

        // 筛选导师编号是 3001 的学生姓名
        List<String> student3001name =  studientList1.stream().map(Studient::getName).collect(Collectors.toList());
        log.info("筛选出导师id是 3001 的学生姓名 {}", student3001name);

        // 筛选导师编号是 3001 的学生 以地址做分组 也就是 数据库操作中的 group by
        Map<String, List<Studient>> stringListMap =  studientList1.stream().collect(Collectors.groupingBy(Studient::getAddress));
        log.info("筛选出导师id是 3001 按照地址分组 {}",stringListMap);

        // 平均值
        double age = studientList1.stream().collect(Collectors.averagingDouble(Studient::getAge));
        log.info("筛选出导师id是 3001 平均年龄 {}", age);

        studientList1.stream().forEach(item -> item.setName(item.getName()+"123"));
        log.info("重新设置姓名是{}", studientList1);

        Studient studient1 = studientList1.stream().filter(item -> item.getAge() < 22).findAny().orElse(new Studient());
        log.info("年龄小于22的随便取一个{}", studient1);

        Studient mixStudent = studientList.stream().min(Comparator.comparing(Studient::getAge)).get();
        log.info("年龄最小的是{}", mixStudent);

    }
}
这篇关于java中流操作-stream的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!