Java教程

java8 stream的使用心得

本文主要是介绍java8 stream的使用心得,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

首先,我们一起看看stream的层次体系关系:

在这里插入图片描述
一般我们直接使用Strem,比如我们需要从一个指定的字符串数组中,查找指定的字符串是否存在
未使用stream的时候:
import org.junit.Test;

import java.util.*;
/**

  • Created by liqi on 2021/7/29
    */
    public class FindStringTest {
    @Test
    public void testFindStr() {
    String findStr = “b”;
    List stringList = Arrays.asList(“a”, “b”, “c”, “d”, “e”);
    boolean match = false;
    for (String data : stringList) {
    if (data.equals(findStr)) {
    match = true;
    break;
    }
    }
    System.out.println(match ? “存在” : “不存在”);
    }
    }

输出:
存在

使用steam:
@Test
public void testFindStrByStream() {
String findStr = “b”;
List stringList = Arrays.asList(“a”, “b”, “c”, “d”, “e”);
boolean result = stringList.stream().anyMatch(x -> x.equals(findStr));
System.out.println(result);
}
输出:
存在

stream的操作符主要分为中间操作符和终止操作符
中间操作:
1.filter
过滤数据,保留 boolean 为 true 的元素,返回一个集合

这篇关于java8 stream的使用心得的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!