Stream—Elegant handling of collection elements

what is

Stram stream is a new feature of jdk8, which is an efficient iterator used to implement internal iteration and process data efficiently. It can implement data filtering, data mapping, data sorting, sorting and other common operations on collection data

Why

1. Strong readability . Compared with the for loop to process collection elements, Stream uses Lambda expressions, which greatly improves the conversion efficiency and program readability;
2. Efficient . Steam provides both serial and parallel modes for processing Convergence operation, parallel mode can make full use of the advantages of multi-core processors, and can improve processing efficiency when processing large data (greater than 10,000); 3.
Convenient , providing commonly used aggregation operation functions;

how to use

Create a simple student class, and follow-up operations will be explained using the student class as a demonstration (single-type collections and entity class collections operate the same, and single-type collections do not need to specify fields)

class Student {
    
    
        private String  name;	//姓名
        private Integer grade;	//年级
        private String  desc;	//备注

        Student(String name,Integer grade) {
    
    
            this.name  = name;
            this.grade = grade;
        }
    }

collect

Aggregated return, used to specify the returned data type, such as return list, piece together string, etc., can also be used for GroudBy classification by specified field

//比如返回List
List<Student> collectList = studentList.stream().collect(Collectors.toList());

fillter

Filter, according to the conditions to obtain the eligible collection elements

//筛选出一年级学生数
long count = studentList.stream().filter(student -> student.getGrade().equals(1)).count();

map

Data mapping, which extracts the elements in the collection and reassembles them into a new collection of elements

//提取所有学生的名字以逗号隔开输出姓名字符串
String studentNameStr = studentList.stream().map(Student::getName).collect(Collectors.joining(","));
//根据信息自动填充备注信息
List<Student> mapList = studentList.stream()
                .map(student -> {
    
    
                    student.setDesc(student.getName() + "是一名" + student.getGrade() + "年级学生");
                    return student;
                })
                .collect(Collectors.toList());

forEach

Perform custom operations on each collection element, which will change the original collection data

//如统一给学生年级数加一
studentList.stream().forEach(student -> student.setGrade(student.getGrade() + 1));

sort

Data sorting, which can be sorted according to the specified field

//根据学生年级数从低到高排序
List<Student> sortedList = studentList.stream().sorted(Comparator.comparing(Student::getGrade)).collect(Collectors.toList());

statistics

Data statistics, you can count the median, average, etc.

IntSummaryStatistics statistics = studentList.stream().mapToInt(Student::getGrade).summaryStatistics();
System.out.println("学生平均年级是 : " + statistics.getAverage() + "年级");
System.out.println("学生中最高年级是 : " + statistics.getMax() + "年级");
System.out.println("学生中最低年级是 : " + statistics.getMin() + "年级");
System.out.println("学生年级数之和 : " + statistics.getSum());

parallelStream

To operate collection data in parallel, you can use multi-threaded capital punishment flow operation to improve efficiency (used in large data operations). The usage is consistent with stram, such as:

count = studentList.parallelStream().filter(student -> student.getGrade().equals(1)).count();
System.out.println("一年级学生共有" + count + "人");

demo code

In stram, except forEach will change the original collection data, other operations will not change the original collection data, and various operations can also be used according to the actual situation

public class Test {
    
    
    @Data
    private static
    class Student {
    
    
        private String name;
        private Integer grade;
        private String desc;

        Student(String name,Integer grade) {
    
    
            this.name  = name;
            this.grade = grade;
        }
    }
    public static void main(String[] args) {
    
    
        Student student1 = new Student("小红",1);
        Student student2 = new Student("小橙",1);
        Student student3 = new Student("小黄",2);
        Student student4 = new Student("小绿",3);
        Student student5 = new Student("小青",4);
        Student student6 = new Student("小蓝",4);
        Student student7 = new Student("小紫",5);
        Student student8 = new Student("小黑",5);
        Student student9 = new Student("小白",6);
        Student student10 = new Student("小明",6);
        List<Student> studentList = new ArrayList<>();
        studentList.add(student1);
        studentList.add(student2);
        studentList.add(student3);
        studentList.add(student4);
        studentList.add(student5);
        studentList.add(student6);
        studentList.add(student7);
        studentList.add(student8);
        studentList.add(student9);
        studentList.add(student10);
        //collect 聚合返回
        //用于指定返回的数据类型,如返回列表,拼凑字符串等
        //比如返回List
        List<Student> collectList = studentList.stream().collect(Collectors.toList());
        System.out.println(collectList);
        //fillter 过滤,筛选出一年级学生数
        long count = studentList.stream().filter(student -> student.getGrade().equals(1)).count();
        List<Student> fillterList = studentList.stream().filter(student -> student.getGrade().equals(1)).collect(Collectors.toList());
        System.out.println("一年级学生共有" + count + "人" + ",他们是" + fillterList);
        //map 数据映射,将源集合中的元素取出组装成新得元素集合
        //如将所有学生的名字以逗号隔开输出字符串
        String studentNameStr = studentList.stream().map(Student::getName).collect(Collectors.joining(","));
        System.out.println("学生名:" + studentNameStr);
        //也可以将原集合数据进行操作后输出
        List<Student> mapList = studentList.stream()
                .map(student -> {
    
    
                    student.setDesc(student.getName() + "是一名" + student.getGrade() + "年级学生");
                    return student;
                })
                .collect(Collectors.toList());
        System.out.println("学生名:" + mapList);
        
		//forEach 对每一个集合元素进行自定义操作,该操作会改变原集合数据
		//如统一给学生年级数加一
		studentList.stream().forEach(student -> student.setGrade(student.getGrade() + 1));
		
        //sorted 排序,可以根据指定字段进行排序(reversed倒序)
        List<Student> sortedList = studentList.stream().sorted(Comparator.comparing(Student::getGrade)).collect(Collectors.toList());
        System.out.println("正序输出学生信息:");
        sortedList.forEach(student -> {
    
    
            System.out.println(student.desc);
        });

        //statistics 统计,可以统计中位数,平均数等
        IntSummaryStatistics statistics = studentList.stream().mapToInt(Student::getGrade).summaryStatistics();
        System.out.println("学生平均年级是 : " + statistics.getAverage() + "年级");
        System.out.println("学生中最高年级是 : " + statistics.getMax() + "年级");
        System.out.println("学生中最低年级是 : " + statistics.getMin() + "年级");
        System.out.println("学生年级数之和 : " + statistics.getSum());

        //parallelStream 并行操作集合数据,可以利用多线程极刑流操作,提高效率(大数据操作时使用),用法以stram一致如:
        count = studentList.parallelStream().filter(student -> student.getGrade().equals(1)).count();
        System.out.println("一年级学生共有" + count + "人");

        //stram中除了forEach会改变原集合数据外,其余操作均不会改变原集合数据,各种操作也可以根据实际情况搭配使用
        //如筛选出三年级及以上年级同学,然后填充备注信息,并根据他们的年级数倒序排序
        List<Student> tempList = studentList.stream().filter(student -> student.getGrade() >= 3).map(student -> {
    
    
            student.setDesc(student.getName() + "是一名" + student.getGrade() + "年级学生");
            return student;
        }).sorted(Comparator.comparing(Student::getGrade).reversed()).collect(Collectors.toList());
        System.out.println("倒序输出三年级及三年级以上学生信息:");
        tempList.forEach(student -> {
    
    
            System.out.println(student.desc);
        });
    }
}

Guess you like

Origin blog.csdn.net/xianren95/article/details/125805197