如何使用 Java 8 流查找较大值之前的所有值?如何使用、较大、Java

2023-09-07 09:54:54 作者:两相知

通过在工作中发布的一些编码 Katas,我偶然发现了这个我不知道如何解决的问题.

Through some coding Katas posted at work, I stumbled on this problem that I'm not sure how to solve.

使用 Java 8 Streams,给定一个正整数列表,生成一个整数在较大值之前的整数列表.

Using Java 8 Streams, given a list of positive integers, produce a list of integers where the integer preceded a larger value.

[10, 1, 15, 30, 2, 6]

上述输入将产生:

[1, 15, 2]

因为 1 在 15 之前,15 在 30 之前,2 在 6 之前.

since 1 precedes 15, 15 precedes 30, and 2 precedes 6.

非流式解决方案

public List<Integer> findSmallPrecedingValues(final List<Integer> values) {

    List<Integer> result = new ArrayList<Integer>();
    for (int i = 0; i < values.size(); i++) {
        Integer next = (i + 1 < values.size() ? values.get(i + 1) : -1);
        Integer current = values.get(i);
        if (current < next) {
            result.push(current);
        }
    }
    return result;
}

我的尝试

我的问题是我不知道如何在 lambda 中访问 next.

What I've Tried

又是一个java牛逼框架

The problem I have is I can't figure out how to access next in the lambda.

return values.stream().filter(v -> v < next).collect(Collectors.toList());

问题

是否可以检索流中的下一个值?我应该使用 map 并映射到 Pair 以便访问下一个吗?

Question

Is it possible to retrieve the next value in a stream? Should I be using map and mapping to a Pair in order to access next?

推荐答案

使用 IntStream.range:

static List<Integer> findSmallPrecedingValues(List<Integer> values) {
    return IntStream.range(0, values.size() - 1)
        .filter(i -> values.get(i) < values.get(i + 1))
        .mapToObj(values::get)
        .collect(Collectors.toList());
}

它肯定比带有大循环的命令式解决方案更好,但就以惯用方式使用流"的目标而言,仍然有点笨拙.

It's certainly nicer than an imperative solution with a large loop, but still a bit meh as far as the goal of "using a stream" in an idiomatic way.

是否可以检索流中的下一个值?

Is it possible to retrieve the next value in a stream?

不,不是真的.我所知道的最好的引用是在 java.util.stream包说明:

Nope, not really. The best cite I know of for that is in the java.util.stream package description:

流的元素在流的生命周期内只被访问一次.像 Iterator 一样,必须生成一个新流来重新访问源的相同元素.

The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.

(检索除当前正在操作的元素之外的元素意味着它们可以被多次访问.)

(Retrieving elements besides the current element being operated on would imply they could be visited more than once.)

我们还可以通过其他几种方式在技术上做到这一点:

We could also technically do it in a couple other ways:

有条不紊(非常好).使用流的 iterator 技术上仍在使用流. Statefully (very meh). Using a stream's iterator is technically still using the stream.
 
精彩推荐
图片推荐