Stream.dropWhile()不会在两个不同的值中返回正确的值 [英] Stream.dropWhile() doesn't return correct value in two different values

查看:77
本文介绍了Stream.dropWhile()不会在两个不同的值中返回正确的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习Java-9的新功能,我开始了解Stream的dropWhile方法,但是它在两种不同的情况下返回了不同的值. 这是我的代码

I am trying to learn new features in Java-9 I come to know about the dropWhile method of Stream but it is returning different values in two different scenarios. Here is my code

package src.module;

import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.List;

public class Test {

    public static void main(String[] args) {

        String s[] = new String[3];
        s[0] = "Hello";
        s[1] = "";
        s[2] = "World";
        List<String> value = Stream.of(s).dropWhile(a -> a.isEmpty()).collect(Collectors.toList());

        System.out.println(value);

        List<String> values = Stream.of("a", "b", "c", "", "e", "f").dropWhile(d -> !d.isEmpty())
                .collect(Collectors.toList());
        System.out.println(values);

    }
}

这是我得到的答案

[Hello, , World]
[, e, f]

我认为在第一个条件下它应该打印[,World]. 预先感谢.

What I think in first condition it should print [,World]. Thanks in advance.

推荐答案

The dropWhile method, introduced in Java 9, will remove the longest starting set of elements that match the predicate.

如果此流是有序的,则在删除与给定谓词匹配的元素的最长前缀之后,返回由该流的其余元素组成的流.

Returns, if this stream is ordered, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate.

因为您的条件是该项目为空,而第一个项目不为空,则什么也没有删除,使["Hello", "", "World"]完好无损.

Because your condition is that the item is empty, and the first item is not empty, nothing is removed, leaving ["Hello", "", "World"] intact.

最后,当您以相反的条件调用dropWhile时,该值不为空,则前三个项目匹配并被删除,剩下的是["", "e", "f"].

At the end, when you call dropWhile with the opposite condition, is not empty, the first 3 items match and are removed, leaving ["", "e", "f"], which are the remaining items.

这是预期的行为.

这篇关于Stream.dropWhile()不会在两个不同的值中返回正确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆