Stream流式操作

2022-10-30  本文已影响0人  鱼落于天
package basic;

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

import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author 海棠无香
 * @since 2022/10/30 7:01 下午
 */
public class StreamTest {
    public final static String MIDDLE_OPERATE = "中间操作";
    public final static String END_OPERATE = "终值操作";

    public static class CustomStream {
        public String operateName;
        public Integer id;
        public String describe;
        public String type;

        public CustomStream(String operateName, Integer id, String describe, String type) {
            this.operateName = operateName;
            this.id = id;
            this.describe = describe;
            this.type = type;
        }


        @Override
        public String toString() {
            return "Stream{" +
                    "operateName='" + operateName + '\'' +
                    ", id=" + id +
                    ", describe='" + describe + '\'' +
                    ", type='" + type + '\'' +
                    '}' + "\n";
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            CustomStream stream = (CustomStream) o;
            return Objects.equals(operateName, stream.operateName) && Objects.equals(id, stream.id) && Objects.equals(describe, stream.describe) && Objects.equals(type, stream.type);
        }

        @Override
        public int hashCode() {
            return Objects.hash(operateName, id, describe, type);
        }
    }

    private List<CustomStream> streams;

    public static void main(String[] args) {
        System.out.println("Stream  Test");
    }

    @Before
    public void beforeTest() {
        this.streams = new ArrayList<>();
        this.streams.add(new CustomStream("filter", 1, "过滤", StreamTest.MIDDLE_OPERATE));
        this.streams.add(new CustomStream("distinct", 2, "去重-根据hashCode和equals方法对比", StreamTest.MIDDLE_OPERATE));
        this.streams.add(new CustomStream("limit", 3, "数据量", StreamTest.MIDDLE_OPERATE));
        this.streams.add(new CustomStream("skip", 4, "去掉前几个", StreamTest.MIDDLE_OPERATE));
        this.streams.add(new CustomStream("map", 5, "类型修改", StreamTest.MIDDLE_OPERATE));
        this.streams.add(new CustomStream("peak", 6, "遍历数据,修改数据等", StreamTest.MIDDLE_OPERATE));
        this.streams.add(new CustomStream("flatMap", 7, "将每个流的内容拼接起来,进行扁平化操作", StreamTest.MIDDLE_OPERATE));
        this.streams.add(new CustomStream("collect", 11, "收集:转为其他格式", StreamTest.END_OPERATE));
        this.streams.add(new CustomStream("anyMatch", 12, "任意一个元素满足条件",  StreamTest.END_OPERATE));
        this.streams.add(new CustomStream("allMatch", 13, "任意全部元素都满足条件",  StreamTest.END_OPERATE));
        this.streams.add(new CustomStream("noneMatch", 14, "任意一个元素都不满足条件",  StreamTest.END_OPERATE));
        this.streams.add(new CustomStream("findAny", 15, "返回流中任意一个元素:Optional对象",  StreamTest.END_OPERATE));
        this.streams.add(new CustomStream("findFirst", 16, "返回流中第一个元素",  StreamTest.END_OPERATE));
        this.streams.add(new CustomStream("forEach", 17, "循环操作",  StreamTest.END_OPERATE));
        this.streams.add(new CustomStream("count", 18, "数量",  StreamTest.END_OPERATE));
        this.streams.add(new CustomStream("reduce", 19, "将结果依次整合",  StreamTest.END_OPERATE));
        this.streams.add(new CustomStream("min", 20, "最大",  StreamTest.END_OPERATE));
        this.streams.add(new CustomStream("max", 21, "最小",  StreamTest.END_OPERATE));

        System.out.println(Objects.equals(this.streams.get(0), this.streams.get(2)));
    }

    /**
     * stream 是流式操作
     */
    @Test
    public void testStream() {
        List<CustomStream> collect = this.streams.stream()
                .filter(i -> i.id > 1)
                .distinct()
                .skip(2)
                .limit(4)
                .map(i -> {
                    System.out.println("map---");
                    // 类型转换 -- 正常应该使用 peak,此处只演示用
                    i.id = i.id * 10;
                    return i;
                })
                .sorted((a, b) -> b.id - a.id) // 倒序
                .peek(i -> System.out.println("peak--"))
                .collect(Collectors.toList());

        System.out.println(collect);
        System.out.println("-----------------");
        System.out.println(this.streams);
    }

    /**
     * 测试 flatMap
     */
    @Test
    public void testFlatMap() {
        List<CustomStream> s1 = new ArrayList<>();
        s1.add(this.streams.get(0));
        s1.add(this.streams.get(1));
        s1.add(this.streams.get(2));

        List<CustomStream> s2 = new ArrayList<>();
        s2.add(this.streams.get(2));
        s2.add(this.streams.get(3));
        s2.add(this.streams.get(4));

        List<List<CustomStream>> lists = new ArrayList<>();

        lists.add(s1);
        lists.add(s2);
        List<CustomStream> collect = lists.stream().flatMap(Collection::stream).filter(i -> i.id > 2).collect(Collectors.toList());
        System.out.println(collect);
    }

    @Test
    public void testEnd() {
        boolean b = this.streams.stream().peek(System.out::println).anyMatch(i -> i.id > 3);
        System.out.println(b);

        Map<Integer, List<CustomStream>> collect = this.streams.stream().collect(Collectors.groupingBy(i -> i.id));
        System.out.println(collect);

        Integer reduce = this.streams.stream().map(i -> i.id).reduce(0, Integer::sum);

        System.out.println(reduce);
    }

    @Test
    public void testGroup() {
        // 分组统计类型数量
        Map<String, Integer> collect = this.streams.stream().collect(Collectors.toMap(i -> i.type, v -> 1, (o, n) -> o + 1));
        // Collectors.toMap 4个参数依次是:key、value、key 重复时的value设置操作、map类型
        TreeMap<String, Integer> collect5 = this.streams.stream().collect(Collectors.toMap(i -> i.type, v -> 1, (o, n) -> o + 1, TreeMap::new));

        // 获取type值重复出现次数在1次之上的内容
        List<String> collect4 = this.streams.stream().collect(Collectors.toMap(i -> i.type, v -> 1, (o, n) -> o + 1))
                .entrySet()
                .stream()
                .filter(i -> i.getValue() > 1)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
        System.out.println(collect4);

        // 按类型进行分组: 一个参数:分组的key
        Map<String, List<CustomStream>> collect1 = this.streams.stream().collect(Collectors.groupingBy(i -> i.type));

        // 分组后,进行统计:求和、平均值或者再分组等操作:两个参数:第一个参数是分组的key,第二个参数是分组后的数据收集方式
        Map<String, Integer> collect2 = this.streams.stream().collect(Collectors.groupingBy(i -> i.type, Collectors.summingInt(i -> i.id)));

        // 指定map类型,默认是hashMap:三个参数:第一个参数是分组的key,第二个参数是map的类型,第三个参数是分组后的数据收集方式
        TreeMap<String, Integer> collect3 = this.streams.stream().collect(Collectors.groupingBy(i -> i.type, TreeMap::new, Collectors.summingInt(i -> i.id)));

        System.out.println(collect3);
    }
}

上一篇下一篇

猜你喜欢

热点阅读