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 @ 2022-06-06 14:27  骚哥  阅读(3075)  评论(0编辑  收藏  举报