【问题标题】:Flatten nested string arrays展平嵌套的字符串数组
【发布时间】:2018-06-11 17:22:32
【问题描述】:

我正在尝试使用流来展平多维字符串数组。我可以用循环来做到这一点,但流似乎是更惯用的方式。我知道this question 但它使用整数特定方法。下面返回一个对象数组,而不是预期的String[]

String[][][] sources = new String[][][]{
           {{"a","b","c"},{"d","e","f"}}
           {{"g","h","i"},{"j","k","l"}}
};
String[] values = Arrays.stream(sources[0])
            .flatMap(Arrays::stream)
            .toArray();

【问题讨论】:

  • .toArray(String[]::new).
  • “而不是预期的字符串[]”如果你读过the Javadoc,你不会期待的。
  • 谢谢,我完全忽略了这一点,并认为问题出在上游
  • 你的数组应该是一个字符数组char[][][] sources = new char[][][]而不是字符串!!
  • @YCF_L 或数组元素实际上是用"s 而非's 声明的。

标签: java


【解决方案1】:

要编译您当前的示例,toArray 应该是:

String[] values = Arrays.stream(sources[0])
                        .flatMap(Arrays::stream)
                        .toArray(String[]::new); // <----------------------

如果您想为sources 执行此操作,您需要使用两次flatMap,然后使用.toArray(String[]::new) 收集到一个数组:

String[] values = Arrays.stream(sources)
                        .flatMap(Arrays::stream)
                        .flatMap(Arrays::stream)
                        .toArray(String[]::new);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 2021-08-21
    • 2014-02-16
    • 2014-05-28
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多