Stream: traverse the collection and filter the data in the collection

Traditional way:
Use the traditional way to traverse the collection and filter the data in the collection

Example:

public class Demo01List {
    
    
    public static void main(String[] args) {
    
    
        //创建一个List集合,存储姓名
        List<String> list = new ArrayList<>();
        list.add("刘亦菲");
        list.add("周芷若");
        list.add("周薇");
        list.add("胡歌");
        list.add("夜轻染");
        list.add("周作人");

        //对list集合中的元素进行过滤,只要以周开头的元素,存储到一个新的集合中
        List<String> list1 = new ArrayList<>();
        for (String s : list) {
    
    
            if(s.startsWith("周")){
    
    
                list1.add(s);
            }
        }
        System.out.println(list1);

        //对list1集合进行过滤,只要姓名长度为3的人,存储在一个新的集合
        List<String> list2 = new ArrayList<>();
        for (String s : list1) {
    
    
            if (s.length()==3){
    
    
                list2.add(s);
            }
        }
        System.out.println(list2);
    }
}

Use Stream:
Use the Stream method to traverse the collection and filter the data in the collection. The
Stream stream appeared after JDK1.8. The
focus is on what to do, not how to do
an example:

public class Demo02Stream {
    
    
    public static void main(String[] args) {
    
    
        //创建一个List集合,存储姓名
        List<String> list = new ArrayList<>();
        list.add("刘亦菲");
        list.add("周芷若");
        list.add("周薇");
        list.add("胡歌");
        list.add("夜轻染");
        list.add("周作人");

        //对list集合中的元素进行过滤,只要以周开头的元素,存储到一个新的集合中
        //对list1集合进行过滤,只要姓名长度为3的,存储到一个新的集合中
        //遍历集合输出
        list.stream()
                .filter(name ->name.startsWith("周"))
                .filter(name -> name.length()==3)
                .forEach(name -> System.out.println(name));
    }
}

Program demonstration:
Insert picture description here
Overview of flow thinking: On the
whole, flow thinking is similar to the "production line" of the factory floor.
When you need to operate on multiple elements (especially multi-step operations), considering performance and convenience, we should first put together a "model" step plan, and then execute it according to the plan.

Remarks: "Stream" is actually a function model of collection elements. It is not a collection or a data structure. It does not store any element (or its address value).

当使用一个流的时候,通常包括三个基本步骤:获取一个数据源(source)
→ 数据转换→执行操作获取想要的结果,每次转换原有 Stream 对象不改变,
返回一个新的 Stream 对象(可以有多次转换),
这就允许对其操作可以像链条一样排列,变成一个管道。

Guess you like

Origin blog.csdn.net/weixin_44664432/article/details/109149874