流2d数组,修剪值并收集回2d数组 [英] Stream 2d array, trim values and collect back to 2d array

查看:89
本文介绍了流2d数组,修剪值并收集回2d数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何想法如何对字符串的二维数组执行修剪操作,例如3x3使用Java流API并收集一个返回相同尺寸的3x3数组?

Any idea how to perform a trim operation on a 2d array of strings e.g. 3x3 using Java stream API and collect one back to same dimension 3x3 array?

关键是要避免使用显式的for循环.

The point is to avoid using explicit for loops.

当前的解决方案是简单地执行如下的for循环:

The current solution would be simply to do a for loop like:

String arr[][] = {
        {"  word  ", "  word  "},
        {"  word  ", "  word  "},
        {"  word  ", "  word  "}};

for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr[i].length; j++) {
        arr[i][j] = arr[i][j].trim();
    }
}

那行得通,但是我正在尝试提出一种与流式API相同的方法.

And that works, but I'm trying to come up with a way to do same with the streaming API.

推荐答案

您可以使用 Arrays.stream 来流式处理数组,如下所示:

You can use Arrays.stream to stream arrays as in:

arr=Arrays.stream(arr).map(s -> Arrays.stream(s).map(a->a.trim()).toArray(String[]::new)).toArray(String[][]::new);

您可以先传输第一个维度,然后再传输第二个维度.

You can stream the 1st dimension first then the second.

这篇关于流2d数组,修剪值并收集回2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆