Stream.findFirst()代替get(0)和数组[0]获取集合中的第一个值

一.介绍

语法

集合.stream().findFirst()

使用

// 我们的工具类(切割SKU字符串relatedSkuJoin,转为集合).stream.第一个数();
CommonUtils.splitStringList(item.getRelatedSkuJoin()).stream().findFirst()

源码

  
复制代码
  /**
     * Returns an {@link Optional} describing the first element of this stream,
     * or an empty {@code Optional} if the stream is empty.  If the stream has
     * no encounter order, then any element may be returned.
     *
     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
     * terminal operation</a>.
     *
     * @return an {@code Optional} describing the first element of this stream,
     * or an empty {@code Optional} if the stream is empty
     * @throws NullPointerException if the element selected is null
     */
    Optional<T> findFirst();
复制代码

 

二.Stream中可以获取集合中的第一个值

案例

目的

获取在SKU集合中的第一个字符串

(不要get(),也可以直接return返回Optional <java.lang.String>)

代码

// 获取productVersions的getRelatedSkuJoin转SKU集合后的第一个字符串
List<String> skus = productVersions.stream().map(item -> {
    // 我们的工具类(切割SKU字符串relatedSkuJoin,转为集合).stream.第一个数().get();
    String relatedSku = CommonUtils.splitStringList(item.getRelatedSkuJoin()).stream().findFirst().get();
    return relatedSku;
}).collect(Collectors.toList());

 

三.Stream中可以获取数组中的第一个值

语法什么的和集合的一样,或者说是这里是把数组转为集合,在进行处理

 

案例

代码

复制代码
    @Test
    public void wzwSplit()
    {
        // 字符串1
        String strOne = "125,123,1234";
​
        // 已逗号分隔转为数组1
        String[] splitOne = strOne.split(",");
        String s1 = Arrays.stream(splitOne).findFirst().get();
​
        System.out.println("s1 = " + s1);
    }
复制代码

结果图

 

posted @   骚哥  阅读(3251)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
点击右上角即可分享
微信分享提示