背景:由于流不存储数据,所以流在操作完成之后需要归集成一个集合;

主要的内容:

personList.stream().collect(Collertors.toSet()),

personList.stream().collect(Collertors.toList()),

personList.stream().collect(Collertors.toMap()),toMap中需要两个

package com.ydlclass.feature;

import org.junit.Before;
import org.junit.Test;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class LambdaTest {
    List<Person> personList = new ArrayList<>();
    List<Integer> simpleList = Arrays.asList(15,22,9,11,33,52,14);
    @Before
    public void initData(){
        personList.add(new Person("张三",3000,23,"男","太原"));
        personList.add(new Person("李四",7000,34,"男","西安"));
        personList.add(new Person("王五",5200,22,"女","西安"));
        personList.add(new Person("小黑",1500,33,"女","上海"));
        personList.add(new Person("狗子",8000,44,"女","北京"));
        personList.add(new Person("铁蛋",6200,36,"女","南京"));
    }
    

    @Test
    public void collectTest(){//将流重新变为一个集合
        //常见的几个api,tolist,toSet,注意toMap时需要一定转化
        List<Integer> collect = simpleList.stream().collect(Collectors.toList());
        Set<Integer> collect1 = simpleList.stream().collect(Collectors.toSet());

        Map<String, Person> collect2 = personList.stream().collect(Collectors.toMap(person -> person.getName(), person -> person));
        System.out.println(collect2);
        //需要两个表达式,前一个表达式负责将person变为key
        //后面的表达式负责将person变为value
        //这样做的好处是,往后就不需要遍历了,直接使用新的返回的map
        System.out.println(collect2.get("张三"));
        /***
         * 输出的结果为:
         * {李四=Person{name='李四', salary=7000, age=34, sex='男', area='西安'}, 张三=Person{name='张三', salary=3000, age=23, sex='男', area='太原'}, 王五=Person{name='王五', salary=5200, age=22, sex='女', area='西安'}, 狗子=Person{name='狗子', salary=8000, age=44, sex='女', area='北京'}, 铁蛋=Person{name='铁蛋', salary=6200, age=36,
         * sex='女', area='南京'}, 小黑=Person{name='小黑', salary=1500, age=33, sex='女', area='上海'}}
         */
    }


}