Stream.dropWhile() 不会 return 在两个不同的值中更正值

Stream.dropWhile() doesn't return correct value in two different values

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

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]。 提前致谢。

dropWhile 的 Javadoc 指出:

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.

在第一个片段中,Stream 的第一个元素不满足 a -> a.isEmpty(),因此没有元素被删除。

在第二个片段中,Stream中的前3个元素满足d -> !d.isEmpty(),所以这3个元素被丢弃,留下"""e"&"f".

在 Java 9 中引入的 dropWhile method 将删除与谓词匹配的最长起始元素集。

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"] 完好无损。

最后,当你用相反的条件调用 dropWhile 时,不为空,前 3 项匹配并被删除,留下 ["", "e", "f"],这是剩余的项目。

这是预期的行为。

你的第一个条件是说在找到非空项目之前丢弃项目第二个条件是说在找到空项目之前丢弃项目。添加一个 '!'到你的第一个条件得到你的预测结果。

为了更好的理解算法,可以尝试更换一个Stream版本:

List<String> value = Stream.of(s).dropWhile(String::isEmpty).collect(Collectors.toList());

使用经典 for 循环:

List<String> value = new ArrayList<>();
boolean dropping = true;

for (int i = 0; i < s.length; i++) {
    String str = s[i];
    if (dropping) {
        if (str.isEmpty()) {
            continue;
        }
        dropping = false;
    }
    value.add(str);
}