美文网首页
java 特性 stream().map()及 stream(

java 特性 stream().map()及 stream(

作者: 一滴矿泉水 | 来源:发表于2023-01-10 18:40 被阅读0次

stream() 相当于一个高级版本的 iterator,iterator 只有简单的遍历功能,而 stream 在这个基础上提供了抽取,过滤,转化,聚合,化简等丰富的流处理功能。

创建学校类

public class School {
    // 获奖类型
    private  String trophyType;
     // 班级人数
    private  int numStudent;
    // 获奖班级
    private  String trophyClass;
    public School(String trophyType, int numStudent, String trophyClass) {
        this.trophyType = trophyType;
        this.numStudent = numStudent;
        this.trophyClass = trophyClass;
    }
}

创建奖金类

public class Bonus {
    // 获奖类型
    private  String trophyType;
    // 获奖班级
    private  String trophyClass;

    public Bonus(String trophyType, String trophyClass) {
        this.trophyType = trophyType;
        this.trophyClass = trophyClass;
    }
}

使用

public void streamMap() throws InterruptedException {

    List<School> schools = Arrays.asList(
            new School("金奖(gold)", 66, "一班"),
            new School("银奖(silver)", 77, "二班"),
            new School("铜奖(bronze)", 88, "三班")
    );
    // 返回奖金 List
    List<String> trophyTypes = schools.stream().map(school -> school.getTrophyType()).collect(Collectors.toList());
    // 实现英文字母转大写 List
    List<String> UpperCaseTypes = trophyTypes.stream().map(String::toUpperCase).collect(Collectors.toList());
    // 数字大小修改 List
    List<Integer> numStudents = schools.stream().map(school -> school.getNumStudent() / 2).collect(Collectors.toList());
    // 组装新的 List
    List<Bonus> bonuses = schools.stream().map(trophy -> {
        return new Bonus(trophy.getTrophyClass(), trophy.getTrophyType());
    }).collect(Collectors.toList());
    // 根据过滤器 筛选 schools中 名字内包含 "金" 字 ,并且长度为 2的学校
    schools.stream().filter((School sc)->sc.getTrophyType().contains("金")).filter((School sc)->sc.getTrophyType().length()==8).forEach((School sc)->{
        System.out.println("符合条件学校 : " + sc);
    });

    System.out.println("upperCaseTypes : " + UpperCaseTypes);
    System.out.println("numStudents : " + numStudents);
    System.out.println("bonuses : " + bonuses);
}

日志输出

符合条件学校 : School{trophyType='金奖(gold)', numStudent='66',     trophyClass='一班'}
upperCaseTypes : [金奖(GOLD), 银奖(SILVER), 铜奖(BRONZE)]
numStudents : [33, 38, 44]
bonuses : [Trophy{trophyType='一班', trophyClass='金奖(gold)'}, Trophy{trophyType='二班', trophyClass='银奖(silver)'}, Trophy{trophyType='三班', trophyClass='铜奖(bronze)'}]

文章持续更新中、希望对各位有所帮助、有问题可留言 大家共同学习.

相关文章

网友评论

      本文标题:java 特性 stream().map()及 stream(

      本文链接:https://www.haomeiwen.com/subject/qquvcdtx.html