【问题标题】:Fill dynamically 2D array - Java [duplicate]动态填充二维数组 - Java [重复]
【发布时间】:2019-02-26 19:17:23
【问题描述】:

我可以在 Java 中按顺序检索以下元素列表,我需要将它们插入到 AxB 维度矩阵中。如何将这些元素按顺序排列到矩阵中?

Element: rainy
Element: hot
Element: high
Element: false
Element: No
Element: rainy
Element: cold
Element: normal
Element: true
Element: yes

我想要的输出是这样的:

array = [[rainy, hot, high, false, No],[rainy, cold, normal, true, yes]]

如何开始?

【问题讨论】:

  • 您至少尝试过解决吗?向我们展示一些您尝试过的代码。
  • 在 java 中查找列表分区。查看此帖子:stackoverflow.com/questions/2895342/…
  • 但我建议你创建一个保存相关数据的类。例如,您可以创建一个类 Weather 或其他内容,其中包含 precipitationtemperature 等字段。

标签: java arrays


【解决方案1】:

这个问题对我来说不是很清楚,但由于我无法发表评论,这里有一个答案:

我将假设您将数据保存在一个数组中(例如String [] dataset),并且希望将其转换为二维数组,因此步骤如下。

首先用你的 AxB 大小初始化二维数组:

int a = dataset.length/5; // the size of your dataset divided by the chuncks
int b = 5; // the size of your chunck
String[][] processedDataset = new String[a][b];

然后你想用你的数据集填充二维数组。这可以通过基本的 for 循环来完成:

int k = 0;
for(int i = 0; i < processedDataset.length; i++){
  for(int j = 0; j < processedDataset[i].length; j++){
    processedDataset[i][j] = dataset[k++];
  }
}

【讨论】:

  • dataset[i+j] 应该是 dataset[i*processedDataset[i].length+j]。另一种选择是使用第三个循环变量k,在外部for 循环中初始化为0,并在内部for 循环中递增,然后访问数据集[k]
  • 感谢@SirRaffleBuffle,相应地编辑了答案。
【解决方案2】:

您可以使用 guava 库进行分区 Guava list partition

List<String> element= //...
List<List<String>> smallerLists = Lists.partition(element, # of partition you want);

【讨论】:

    猜你喜欢
    • 2016-08-07
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 2017-04-17
    相关资源
    最近更新 更多