停止在lambda内部

huangapple go评论75阅读模式
英文:

Stop inside lambda

问题

Here is the translated code portion:

这里是我的代码:

taskQueues.stream().
        filter(aDeque -> !aDeque.isEmpty()).
        map(decks -> decks.stream()). // Breakpoint. Evaluate.
        sorted((a, b) -> {
            return 1;
        });

我已翻译了您提供的代码部分。

英文:

Here is my code:

taskQueues.stream().
        filter(aDeque -> !aDeque.isEmpty()).
        map(decks -> decks.stream()). // Breakpoint. Evaluate.
        sorted((a, b) -> {
            return 1;
        });

I have marked where breakpoint is put. The image depicts that the stream is not empty. Therefore, I expected that I'll be able to compare something. But I have failed.

停止在lambda内部

The problem is that I'll be able to understand how to sort only when I stop inside that lambda and have a look at the two objects at hand.

I would like to:

  1. Understand the reason why the debugger doesn't stop at line 42.
  2. Understand how to make the debugger stop there.

答案1

得分: 4

  1. 首先,你必须使用 flatMap 而不是 map,否则你只是对集合进行排序,而不是对集合的实际元素进行排序。更多信息在这里

  2. 关于为什么断点没有在那里停止,Java流需要进行终端操作才能进行评估 - sorted 不是终端操作,因此只需在末尾添加终端操作,例如 toList().forEach(System.out::println),就可以解决问题。

更多信息 关于Java中的终端操作。

修正后的版本应该是:

taskQueues.stream()
        .filter(aDeque -> !aDeque.isEmpty())
        .flatMap(decks -> decks.stream()) // 断点。评估。
        .sorted((a, b) -> {
            return 1;
        })
        .forEach(System.out::println);

<details>
<summary>英文:</summary>

There are 2 things wrong here:

1. First of all you have to use `flatMap` and not `map` otherwise you are just sorting Collections and not the actual elements of the collection. More info [here][1]

2. Regarding why the breakpoint is not stopping there, java streams require terminal operations to be evaluated - `sorted` is NOT a terminal operation, so simply adding a terminal operation at the end, such as `toList()` or `.forEach(System.out::println)`, should do the trick.

[More info][2] on terminal operations in java

Corrected version would then be:

taskQueues.stream()
.filter(aDeque -> !aDeque.isEmpty())
.flatMap(decks -> decks.stream()) // Breakpoint. Evaluate.
.sorted((a, b) -> {
return 1;
})
.forEach(System.out::println);



  [1]: https://www.baeldung.com/java-difference-map-and-flatmap
  [2]: https://www.baeldung.com/java-8-streams#pipeline

</details>



huangapple
  • 本文由 发表于 2023年5月21日 14:32:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定