gpt4 book ai didi

java - 有什么方法可以仅使用 `map` 而不使用 `flatMap` 将 2D 列表转换为 1D 列表?

转载 作者:行者123 更新时间:2023-12-03 11:18:33 29 4
gpt4 key购买 nike

我是 Java 初学者,刚开始学习 mapflatMap .
当 2d List 应该转换为 1d List 时,它是如下实现的。

List<List<Integer>> list_2d = List.of(List.of(1, 2), List.of(3, 4));

List<Integer> lst1 = list_2d
.stream()
.flatMap(arr -> arr.stream())
.collect(Collectors.toList());
printAll(lst1); // [1, 2, 3, 4]
但是,我认为它看起来可以不使用 flatMap 来实现。 .
有什么办法可以让代码具有相同的逻辑,只需使用 map ,不使用 flatMap ?
只是问,因为如果 map可以全部替换 flatMap ,没有理由背诵 flatMap .我总是追求简单和基本的东西。

最佳答案

要回答这个问题,还有其他方法,但我不会推荐我能想到的任何方法。例如,您可以使用减少:

    List<List<Integer>> list2d = List.of(List.of(1, 2), List.of(3, 4));

List<Integer> lst1 = list2d
.stream()
.reduce((l1, l2) -> {
ArrayList<Integer> concatenated = new ArrayList<>(l1);
concatenated.addAll(l2);
return concatenated;
})
.orElse(List.of()); // or else empty list

System.out.println(lst1);
输出与您的相同:

[1, 2, 3, 4]


但是你的代码比我的更容易理解。我建议你坚持下去。
map() 和 flatMap() 不能互换吗?

Just because, if map can replaced all of flatMap, there are no reasonto memorize flatMap. I always pursue simple and basic thing.


你已经得到了最简单和最基本的东西。此外,为了充分发挥流的潜力,您需要不时使用许多方法调用。在使用流多年之后,我仍然发现自己有时会在 Javadoc 中查找它们。我得查一下 reduce()的详情对于这个答案。不要指望一切都在你的脑海中。我知道 flatMap()但是,请记住,因为它通常很实用。
编辑:仅出于学术兴趣:通常您不能替换 flatMap()map() .或者你会使用 map()从一开始。但反过来说:您可以随时替换 map()flatMap() .你只是不想。例如,如果我们有:
    List<String> strings = List.of("short", "somewhat longer");
List<Integer> lengths = strings.stream()
.map(String::length)
.collect(Collectors.toList());
System.out.println(lengths);

[5, 15]


如果出于某种奇怪的原因我们只能记住 flatMap() ,不是 map() ,我们可以这样做:
    List<Integer> lengths = strings.stream()
.flatMap(s -> Stream.of(s.length()))
.collect(Collectors.toList());
不过,我认为很明显,它给我们带来的只是不必要的复杂化。最好同时记住 map()flatMap()至少足以在我们需要它们时查找它们。

关于java - 有什么方法可以仅使用 `map` 而不使用 `flatMap` 将 2D 列表转换为 1D 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65378828/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com