将数组分成3个块,并将它们放入数组数组中?

我一直在尝试找到我的问题的解决方案,我有一个调用的数组,我想将其划分为数组(foodsArray),因此每个数组包含3个对象。例如:FoodsfoodsFood[[Food1, Food2, Food3], [Food4, Food5, Food6]]


我目前已经实现了我的问题,就像这样:


Food[] foods = new Food[foodData.length]; //loaded in from a file

List<Food> foodsArray = new ArrayList<Food>();


for(int i=0;i<foods.length;i+=5){

   foodsArray.add(Arrays.copyOfRange(foods, i, Math.min(foods,i+5))); //error is here

   //Output

   System.out.println(Arrays.toString(Arrays.copyOfRange(foods, i, Math.min(foods,i+5))));

}

当前结果(食物阵列):[[Lcom.company.Food;@3c756e4d, [Lcom.company.Food;@7c0e2abd, [Lcom.company.Food;@48eff760, [Lcom.company.Food;@402f32ff]


预期结果(食物阵列):


[[com.company.Food@458ad742, com.company.Food@48eff760, com.company.Food@402f32ff],

 [com.company.Food@6d8a00e3, com.company.Food@548b7f67, com.company.Food@7ac7a4e4],

 [com.company.Food@5dfcfece]]


一只甜甜圈
浏览 111回答 2
2回答

拉风的咖菲猫

这又如何!您只需循环访问数组并将其中三个添加到列表中,然后在每个三个列表之后,将列表添加到另一个列表,然后重置初始列表。ArrayList<ArrayList<Food>> result = new ArrayList<>();ArrayList<Food> subArray = new ArrayList<>();for (int i = 0; i < foods.length; i++) {&nbsp; &nbsp; subArray.add(foods[i]);&nbsp; &nbsp; if (i % 3 == 2) {&nbsp; &nbsp; &nbsp; &nbsp; result.add(subArray);&nbsp; &nbsp; &nbsp; &nbsp; subArray = new ArrayList<>();&nbsp; &nbsp; }}很好,很简单。正如Nicholas K所建议的,我正在使用一个List<List<Food>>

素胚勾勒不出你

迟到的聚会,但这里是Java 8解决方案:Food[][] partition(Food[] foods, int groupSize) {&nbsp; return IntStream.range(0, foods.length)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .boxed()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.groupingBy(index -> index / groupSize))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .values()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(indices -> indices&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(index -> foods[index])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toArray(Food[]::new))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toArray(Food[][]::new);}实际上,方法允许将数组划分为任意大小的组。partitiongroupSize如果出现问题,将通过以下电话获得所需的结果:Food[][] result = partition(foods, 3);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java