每天睡觉前30分钟阅读_day1_Java流处理

本文通过实例展示了Java流(Stream)在处理集合时的简洁性和效率,包括普通循环与流式处理的对比,以及并行流的使用。代码中读取文件内容,分割单词,并统计长度大于12的单词数量,流式处理使得代码更加易读和高效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 流的核心思想:我们可以说明想要完成什么任务,而不是说明如何去实现它,将操作的调度留给具体实现去解决。
2.在处理集合时,通常会迭代遍历他的元素,并在每个元素上执行某项操作。使用流时,相同的操作,处理更简介,具体实现操作看代码。
3. 代码包含普通迭代的过程和流处理的过程。
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * @Author Janson
 * @Date 2022/4/16 9:02
 * @Version 1.0
 */
public class Day1Stream {
    public static void main(String[] args) throws IOException {

        Path path = Paths.get("testData/longWord");
        //String  string = Files.readAllBytes.;
        String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
        List<String> words = Arrays.asList(contents.split("\\PL+"));
        int count = 0;
        //普通循环处理
        for (String word : words) {
            if (word.length()>=12){
                count++;
                System.out.println(word);
            }
        }
        System.out.println(count);
         count = 0;
    //    流式处理,stream 和 parallelStream 都是基于 collection接口的
        count = (int) words.stream()
                .filter(word -> word.length()>=12) //lambda表达式
                .count();
        System.out.println(count);

        //并行流式处理
        count = 0;
        count = (int)words.parallelStream().filter(word -> word.length()>=12).count();
        System.out.println(count);

        Stream<String> hello = Stream.of("hello", "my", "name");
        System.out.println(hello);
        Stream<String> stringStream = Stream.of(contents.split("\\PL+"));
    }
}

感受一下流操作吧,处理是不是比普通迭代更方便了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Janson666

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

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

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

打赏作者

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

抵扣说明:

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

余额充值