Java-8-Stream接口

本文详细介绍了Java 8中的Stream接口,包括如何生成Stream、使用Stream的各种中间操作(如filter、map、flatMap、distinct、sorted等)以及终端操作(如forEach、reduce、collect等)。通过实例展示了每个方法的使用方式,帮助理解Stream API的高效数据处理能力。
摘要由CSDN通过智能技术生成

Java-8-Stream接口

interface Stream

思维导图:

在这里插入图片描述

生成 Stream

Stream.of

静态方法(源码):


    public static<T> Stream<T> of(T t) {
        return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
    }

    public static<T> Stream<T> of(T... values) {
        return Arrays.stream(values);
    }



使用
public class M1 {


    public static void main(String[] args) {

//        /*************流的来源*************/
        // 1、of方法
        //      of(T... values):返回含有多个T元素的Stream
        //      of(T t):返回含有一个T元素的Stream

        Stream<String> stream1 = Stream.of(
                "a","b","c","d","e"
        );

        stream1.forEach(System.out::println);

        System.out.println("--------------------");

        String[] strings = {"a","45","a"};

        Stream<String> stream2 = Stream.of(strings);

        stream2.forEach(System.out::println);

    }
}

generate与iterate

源码:

public static<T> Stream<T> generate(Supplier<T> s) {
       //...
}


public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f){
                //...      
}
generate

public class M2 {


    public static void main(String[] args) {

        // generator方法,返回一个无限长度的Stream,其元素由Supplier接口的提供。

        Stream<String> stream1 = Stream.generate(
                () ->
                        "A"
        );

//        stream1.forEach(System.out::println);

        Stream<Double> stream2 = Stream.generate(
                ()->
                        Math.random()
        );

//        stream2.forEach(System.out::println);

        Stream<String> stream3 = Stream
                .generate(() -> "love")
                .limit(10);

        stream3.forEach(System.out::println);
        
    }
}


iterate

public class M3 {

    public static void main(String[] args) {

        //  iterate方法,返回的也是一个无限长度的Stream,与generate方法不同的是,其是通过函数f迭代对给指定的元素种子而产生无限连续有序Stream,其中包含的元素可以认为是:seed,f(seed),f(f(seed))无限循环
        Stream<Integer> stream1 = Stream.iterate(
                1,integer -> integer + 2
        );

        stream1.limit(10).forEach(System.out::println);

        System.out.println("---------------------");
        //生成一个等差数列

        Stream.iterate(0, n -> n + 3).limit(10). forEach(x -> System.out.print(x + " "));


    }
}


合并Stream

源码:


 public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) {
        //...       
}
使用

public class M4 {


    public static void main(String[] args) {

        Stream<Integer> stream1 = Stream.of(
                1,2,3,4,56
        );

        Stream<Integer> stream2 = Stream.of(
                11,258,5689
        );

        Stream<Integer> stream3 = Stream.concat(stream1,stream2);

        stream3.forEach(System.out::println);

        System.out.println("---------");

//        合并多个流(Streams)


        Stream<Integer> first = Stream.of(1, 2);
        Stream<Integer> second = Stream.of(3,4);
        Stream<Integer> third = Stream.of(5, 6);
        Stream<Integer> fourth = Stream.of(7,8);

        Stream<Integer> resultingStream = Stream.concat(first,Stream.concat(second,Stream.concat(third, fourth)));

        resultingStream.forEach(System.out::println);

        System.out.println("---------");


        //合并stream并保留唯一性

        Stream<Integer> firstStream = Stream.of(1, 2, 3, 4, 5, 6);
        Stream<Integer> secondStream = Stream.of(4, 5, 6, 7, 8, 9);

        Stream<Integer> resultingStream_1 = Stream.concat(firstStream, secondStream)
                .distinct();

        resultingStream_1.forEach(System.out::println);


    }
}


中间操作—filter

源码:


Stream<T> filter(Predicate<? super T> predicate);


使用

public class M1 {


    public static void main(String[] args) {

        //filter 对原Stream按照指定条件过滤,过滤出满足条件的元素。

        List<Integer> integers = Create_Data.supply_Integers();

        Predicate<Integer> predicate = integer ->
                integer > 15;

        // 通过传递predicate

        integers.stream()
                .filter(predicate)
                .forEach(System.out::println);


        System.out.println("---------------------------");
        // 直接使用Lambda

        integers.stream()
                .filter(integer -> integer > 75 && integer < 85)
                .forEach(System.out::println);



        System.out.println("---------------------------");


        List<Integer> list  = Arrays.asList(3, 12, 23, 44, 20, 10, 17, 8);

        System.out.println("---List with even Numbers---");

        List<Integer> evenList = list.stream()
                .filter(integer -> integer % 2 ==0)
                .collect(Collectors.toList());


        evenList.forEach(System.out::println);

        System.out.println("\n---List with odd Numbers---");
        List<Integer> oddList = list.stream().filter(i -> i%2 == 1)
                .collect(Collectors.toList());
        oddList.forEach(s -> System.out.print(s+" "));


    }
}


中间操作—map

源码:


//Returns a stream consisting of the elements of this stream that match the given predicate.
<R> Stream<R> map(Function<? super T, ? extends R> mapper);


map方法,它会接受一个函数作为参数。这个函数会被应用到每个元素上,并将其映射成一个新的元素(使用映射一词,是因为它和转换类似,但其中的细微差别在于它是“创建一个新版本”而不是去“修改”)

使用

public class M1 {


    public static void main(String[] args) {

        //map方法将对于Stream中包含的元素使用给定的转换函数进行转换操作,新生成的Stream只包含转换生成的元素。

        List<String> strings = Create_Data.supply_Strings(1,10);

        System.out.println(strings);

        System.out.println("");

        strings.stream()
                .map(s -> s.toLowerCase())
                .forEach(System.out::println);


        System.out.println("----------------");

        List<Person> personList = Create_Data.supply_Persons();

        List<Integer> ages = personList.stream()
                .map(Person::getAge)
                .collect(Collectors.toList());

        ages.forEach(System.out::println);

        System.out.println("---------------");

        Stream<Integer> stream = Stream.of(1,2,4,5,6,8);

        stream.map(integer -> integer * integer)
                .forEach(System.out::println);

    }
}

中间操作—mapToInt mapToLong mapToDouble

为了提高处理效率,官方已封装好了,三种

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值