java8常用新特性

该段代码复制后根据自己需求调整运行

import javax.print.DocFlavor;
import java.util.*;
import java.util.stream.Collectors;

public class Maim {
    public static void main1(String[] args) {
        //模拟查出分页的学生数据
        List<Student> studentList = getStudentData();
        //模拟通过学号查出所有的课程
        List<Course> courseList = getCourseData();
        //分类
        Map<Integer, List<Course>> collect = courseList.stream().collect(Collectors.groupingBy(Course::getId));
        System.out.println("这是将课程list变成的map数据");
        collect.forEach((key,value)->{
            System.out.println(key + "===" + value);
        } );
        System.out.println("给学生list中添加所属的课程");
        //如果没有,则list中会set null
        studentList.forEach(e->{
            e.setCourseList(collect.get(e.id));
            System.out.println(e.toString());
        });

        for (int i = 0; i < studentList.size(); i++) {
            System.out.println(studentList.get(i));
        }

        //生成一个新的map
        //放入map中 (k1,k2)->k1)解决list中有重复数据问题,有则用第一个,不然会报错
        Map<Integer, String> collectMap = studentList.stream().collect(Collectors.toMap(e -> e.getId(), e -> e.getName(),(k1,k2)->k1));
        System.out.println("list生成指定map");
        collectMap.forEach((key,value) ->{
            System.out.println(key+"---"+value);
        });

        //获取list中所有的id集合
        List<Integer> studentIds = studentList.stream().map(e -> e.getId()).collect(Collectors.toList());
        System.out.println("获取到的list中的id");
        studentIds.forEach(e ->{
            System.out.println(e);
        });

        System.out.println("使用distinct给list去重");
        studentIds = studentIds.stream().distinct().collect(Collectors.toList());
        studentIds.forEach(e->{
            System.out.println(e);
        });

        //获取list中的所有id并以都逗号拼接成string
        String ids = studentList.stream().map(e -> e.getId() + ",").collect(Collectors.joining());
        System.out.println(ids.substring(0,ids.length()-1));

        //去重distinct 如果是实体类,需要给实体类重写hashCode()和equals()方法
        courseList = courseList.stream().distinct().collect(Collectors.toList());
        System.out.println("使用distinct去重list");
        courseList.forEach(e ->{
            System.out.println(e);
        });
    }

    public static void main(String[] args) {
        List<Student> studentList = getStudentData();
        // 1. 筛选出名字长度为3的
        // 2. 名字前面拼接 This is
        // 3. 遍历输出
        studentList.stream()
                .filter(student -> student.getName().length() == 3 || student.getName().length() == 2)
                .map(student -> "This is " + student)
                .forEach(student -> {
                    System.out.println(student);
                });
        studentList.forEach(student -> System.out.println(student));

        // 转换成为大写然后收集结果,遍历输出
        List<String> nameList = Arrays.asList("Darcy", "Chris", "Linda");
        List<String> upperCaseNameList = nameList.stream().map(String::toUpperCase).collect(Collectors.toList());
        upperCaseNameList.forEach(e -> System.out.println(e));

        // 查找第一个数据
        List<Integer> numberList = Arrays.asList(1, 1, 2, 3, 4, 5, 6, 7, 8, 9);
        Optional<Integer> number = numberList.stream().findFirst();
        System.out.println(number.orElse(-1));

        // List转数组
        Integer[] toArray = numberList.stream().toArray(Integer[]::new);
        System.out.println(toArray.length);

        // 以逗号拼接
        String toString = numberList.stream().map(number1 -> String.valueOf(number1)).collect(Collectors.joining(","));
        System.out.println(toString);

        // limit / skip 获取或者扔掉前 n 个元素
        List<Integer> ageList = Arrays.asList(11, 22, 13, 14, 25, 26);
        ageList.stream().limit(3).forEach(e -> System.out.println(e));
        System.out.println("-----------------");
        ageList.stream().skip(3).forEach(e -> System.out.println(e));

        // Statistics - 数学统计功能,求一组数组的最大值、最小值、个数、数据和、平均数等
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
        IntSummaryStatistics stats = list.stream().mapToInt(x -> x).summaryStatistics();
        System.out.println("最小值:" + stats.getMin());
        System.out.println("最大值:" + stats.getMax());
        System.out.println("个数:" + stats.getCount());
        System.out.println("和:" + stats.getSum());
        System.out.println("平均数:" + stats.getAverage());

        // partitioningBy - 按某个条件分组
        Map<Boolean, List<Integer>> ageMap = ageList.stream().collect(Collectors.partitioningBy(age -> age > 18));
        System.out.println("未成年人:" + ageMap.get(false));
        System.out.println("成年人:" + ageMap.get(true));

    }

    public static List<Student> getStudentData(){
        return Arrays.asList(
                new Student("张三", 1),
                new Student("张三1", 1),
                new Student("王五", 3),
                new Student("李四", 2));
    }

    public static List<Course> getCourseData(){
        return Arrays.asList(
                new Course(1, "语文", 98),
                new Course(1, "数学", 98),
                new Course(1, "数学", 98),
                new Course(3, "语文", 78),
                new Course(2, "数学", 56));
    }

}
class Student{
    String name;
    int id;
    List<Course> courseList;

    public Student(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Course> getCourseList() {
        return courseList;
    }

    public void setCourseList(List<Course> courseList) {
        this.courseList = courseList;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", courseList=" + courseList +
                '}';
    }
}
class Course{
    int id;
    String courseName;
    int score;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Course(int id, String courseName, int score) {
        this.id = id;
        this.courseName = courseName;
        this.score = score;
    }

    public Course() {
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "Course{" +
                "id=" + id +
                ", courseName='" + courseName + '\'' +
                ", score=" + score +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Course course = (Course) o;
        return id == course.id &&
                score == course.score &&
                courseName.equals(course.courseName);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, courseName, score);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值