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 的元素,返回一个集合 @Test
public void testFilterByStream() {
List integerList = Arrays.asList(10, 11, 53, 1, 57, 9);
System.out.println(integerList.stream().filter(x -> x > 30).collect(Collectors.toList()));
}

2.map(T -> R)
转换操作符,可以做数据转换,比如:把字符串转换成int、long、double,或者把一个实体转换成另外一个实体。包含:map,mapToInt、mapToLong、mapToDouble
@Test
public void testMapByStream() {
List integerList = Arrays.asList(10d, 11d, 53d, 1d, 57d, 9d);
integerList.stream().mapToInt(x->x.intValue()).forEach(System.out::println);
}

未完待续

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值