【JAVA进阶】Stream流

📃个人主页:个人主页

🔥系列专栏:JAVASE基础

目录

1.Stream流的概述

2.Stream流的获取

3.Stream流的常用方法


1.Stream流的概述

什么是Stream流?

  • 在Java 8中,得益于Lambda所带来的函数式编程, 引入了一个全新的Stream流概念。
  • 目的:用于简化集合和数组操作的API。

 Stream流思想

Stream流式思想的核心:

  1. 先得到集合或者数组的Stream流(就是一根传送带)
  2. 把元素放上去
  3. 然后就用这个Stream流简化的API来方便的操作元素。

体验Stream流的作用

假设我们有一个Person类,其中包含属性name和age。我们有一个List<Person>对象,现在我们要使用Java Stream流来过滤出其中年龄大于18岁的人的名字。

public class Main {

    public static void main(String[] args) {

        List<Person> people = new ArrayList<>();
        people.add(new Person("Mike", 20));
        people.add(new Person("John", 17));
        people.add(new Person("Lucy", 25));

        people.stream().filter(p -> p.getAge() > 18).forEach((s-> System.out.println(s.getName())));
  


    }
}

输出:

Mike
Lucy

2.Stream流的获取

Stream操作集合或者数组的第一步是先得到Stream流,然后才能使用流的功能。

集合获取Stream流的方式

可以使用Collection接口中的默认方法stream​()生成流

名称

说明

default Stream<E> stream​()

获取当前集合对象的Stream流

public class Main {

    public static void main(String[] args) {

//----------------- Collection集合获取流------------------------
        Collection<String> list = new ArrayList<>();
        Stream<String> stream = list.stream();
//----------------- Map集合获取流------------------------
        HashMap<String,Integer> map = new HashMap<>();
        //键流
        Stream<String> keyStream = map.keySet().stream();
        //值流
        Stream<Integer> valueStream = map.values().stream();
        //键值对流(拿整体)
        Stream<Map.Entry<String, Integer>> entryStream = map.entrySet().stream();


    }
}

数组获取Stream流的方式

名称

说明

public static <T> Stream<T> stream(T[] array)

获取当前数组的Stream流

public static<T> Stream<T> of(T... values) 

获取当前数组/可变数据的Stream流

    public static void main(String[] args) {
        String[] names=["热爱","编程的","小白白"];
        Stream<String> stream = Arrays.stream(names);
        Stream<String> stringStream = Stream.of(names);


    }

Stream流有三类方法:

  1. Intermediate(中间操作):对数据进行处理和转换,返回一个新的Stream对象,可以链式操作。包括常用的map、filter、distinct等方法。

  2. Terminal(终止操作):对Stream流进行聚合或收集操作,触发执行计算并返回结果。包括常用的forEach、reduce、collect等方法。

  3. Short-circuiting(短路操作):在满足一定条件时可以提前结束Stream流的操作。包括常用的anyMatch、allMatch、noneMatch等方法。

3.Stream流的常用方法

collect():将流中的元素收集到一个容器中。

List<String> words = Arrays.asList("hello", "world", "java", "stream", "api");
Set<String> wordSet = words.stream().collect(Collectors.toSet());
System.out.println(wordSet);

上述代码中,我们定义了一个包含字符串的List,使用Stream的collect()方法对其进行收集操作,将其结果保存在Set集合中,去除重复元素,最终将结果保存在wordSet的Set集合中,并打印输出。

Stream流的常用API中间操作方法包括:

1.filter():根据指定的条件过滤元素。

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> result = list.stream().filter(num -> num % 2 == 0).collect(Collectors.toList());
System.out.println(result);

上述代码中,我们定义了一个包含整数的List,并使用Stream的filter()方法对其进行过滤,只保留其中的偶数,最终将结果保存在result的List中,并打印输出。

2.distinct():根据元素的 hashCode() 和 equals() 方法去重。

List<String> words = Arrays.asList("hello", "world", "hello", "java", "world");
List<String> uniqueWords = words.stream().distinct().collect(Collectors.toList());
System.out.println(uniqueWords);

上述代码中,我们定义了一个包含字符串的List,使用Stream的distinct()方法对其进行去重操作,最终将结果保存在uniqueWords的List中,并打印输出。

3.limit():限制元素数量。

List<String> words = Arrays.asList("hello", "world", "java", "stream", "api");
List<String> limitedWords = words.stream().limit(3).collect(Collectors.toList());
System.out.println(limitedWords);

上述代码中,我们定义了一个包含字符串的List,使用Stream的limit()方法对其进行限制操作,只保留前3个元素,最终将结果保存在limitedWords的List中,并打印输出。

4.skip():跳过指定数量的元素。

List<String> words = Arrays.asList("hello", "world", "java", "stream", "api");
List<String> skippedWords = words.stream().skip(2).collect(Collectors.toList());
System.out.println(skippedWords);

上述代码中,我们定义了一个包含字符串的List,使用Stream的skip()方法对其进行跳过操作,跳过前2个元素,只保留后面的元素,最终将结果保存在skippedWords的List中,并打印输出。


5.concat():合并a和b两个流为一个流

Stream<String> stream1 = Stream.of("Java", "is", "cool");
Stream<String> stream2 = Stream.of(" and", "fun", "too!");

Stream<String> resultStream = Stream.concat(stream1, stream2);
resultStream.forEach(System.out::print); // Output: Java is cool and fun too!

在这个例子中,我们首先创建两个字符串流 stream1 和 stream2,并使用 concat() 方法将它们连接在一起,形成一个新的流 resultStream。最后,我们遍历新的流,并将结果输出到控制台。

总之,Stream.concat() 方法可以将两个流连接为一个流,以便进行进一步的操作。

注意:

  • 中间方法也称为非终结方法,调用完成后返回新的Stream流可以继续使用,支持链式编程。
  • 在Stream流中无法直接修改集合、数组中的数据。

Stream流的常见终结操作方法:

1.forEach()  对此流的每个元素执行遍历操作

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream().forEach(n -> System.out.println(n));

2.count()  返回此流中的元素数  

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
long count = numbers.stream().count();
System.out.println("Count: " + count);

注意:终结操作方法,调用完成后流就无法继续使用了,原因是不会返回Stream了。

收集Stream流:

收集Stream流的含义:就是把Stream流操作后的结果数据转回到集合或者数组中去。

  • Stream流:方便操作集合/数组的手段。
  • 集合/数组:才是开发中的目的。

Stream流的收集方法:

名称

说明

R collect​(Collector collector)

开始收集Stream流,指定收集器

 Collectors工具类提供了具体的收集方式:

名称

说明

public static <T> Collector toList​()

把元素收集到List集合中

public static <T> Collector toSet​()

把元素收集到Set集合中

public static  Collector toMap​(Function keyMapper , Function valueMapper)

把元素收集到Map集合中

 上面案例有使用过,所以就不举例子了....

  • 10
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

热爱编程的小白白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值