The Stream stream of the new Java8 feature modifies the map collection and returns a new map

Introduction to Stream

A new feature introduced by Java8, Stream, as a highlight of Java 8, is a completely different concept from InputStream and OutputStream in the java.io package. It is also different from StAX's Stream for XML parsing, nor is it the Stream for Amazon Kinesis' real-time processing of big data. Stream in Java 8 is an enhancement to the collection (Collection) object function, which focuses on various very convenient and efficient aggregation operations (aggregate operation) or bulk data operations (bulk data operation) on collection objects. The Stream API greatly improves programming efficiency and program readability by means of the same emerging Lambda expression. At the same time, it provides serial and parallel modes for aggregation operations. The concurrent mode can take full advantage of the advantages of multi-core processors, using fork/join parallel mode to split tasks and speed up the processing process.

So what exactly is a stream?

Stream is not a collection element, it is not a data structure and does not store data, it is about algorithms and calculations, it is more like an advanced version of Iterator. In the original version of Iterator, the user can only explicitly traverse the elements one by one and perform certain operations on them; in the advanced version of Stream, the user only needs to specify what operations need to be performed on the elements contained in it, such as "filter out elements whose length is greater than 10 String", "get the first letter of each string", etc., Stream will traverse implicitly internally and make corresponding data conversion.

Stream is like an iterator (Iterator), one-way, non-reciprocating, data can only be traversed once, and it will be used up after traversing once, just like water flowing in front of you, never to return.

Unlike iterators, Stream can be operated in parallel, while iterators can only be operated imperatively and serially. As the name implies, when traversing in serial mode, each item is read before reading the next item. When using parallel traversal, the data will be divided into multiple segments, each of which is processed in a different thread, and the results are output together.

Case presentation

We may have such a requirement in the project: Change the returned Map<String, Object> to Map<String, Object. Field>

Next, I will use the peek method of stream to perform conversion operations. What is peek?

peek performs an operation on each element and returns a new Stream.

Go directly to the Demo code:

package com.star.util;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class Demo {

    static class Student{//只是为了方便演示

        private Integer id;
        private String  name;

        public Integer getId() {
            return id;
        }

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

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
        public Student(Integer id, String name) {
            this.id = id;
            this.name = name;
        }
    }

    public static void main(String[] args) {

        //测试数据,实际中map可能来自数据库或其他方。
        Map<String,Object> map = new HashMap<>();
        map.put("a",new Student(1,"张三"));
        map.put("b",new Student(2,"李四"));
        map.put("c",new Student(3,"王五"));
        map.put("d",new Student(4,"赵六"));

        //需求是将Map<String,Object>改为Map<String,Object.字段>
        Map<String, Object> collect = map.entrySet()//获取集合
                .stream()//获取流
                .peek(obj -> obj.setValue(((Student) obj.getValue()).getName()))//peek支持在每个元素上执行一个操作并且返回新的stream
                // ,我们就利用这个方法转换数据
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));//collect方法用来将流转到集合对象

        //遍历输出
        collect.forEach((key,value)->System.out.println(key+":"+value));
    }

}

Test Results

It can be seen that it has been transformed into the data form we want. There are many very useful features about Stream, such as filtering, sorting, aggregation, matching, etc. I won’t expand too much here. If you are interested, I recommend one from IBM. Official article: Detailed Stream API in Java8 .

Supongo que te gusta

Origin blog.csdn.net/m0_54850467/article/details/126725693
Recomendado
Clasificación