Reputation: 97
I've been trying to find a solution to my problem, I have an array of Foods
called foods
that I want to divide into an array of arrays (foodsArray) so each array contains 3 Food
objects. For example: [[Food1, Food2, Food3], [Food4, Food5, Food6]]
I've currenly implemented my problem like that:
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))));
}
Current outcome (foodsArray): [[Lcom.company.Food;@3c756e4d, [Lcom.company.Food;@7c0e2abd, [Lcom.company.Food;@48eff760, [Lcom.company.Food;@402f32ff]
Expected outcome (foodsArray):
[[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]]
Upvotes: 0
Views: 83
Reputation: 4365
Late to the party, but here is Java 8 solution:
Food[][] partition(Food[] foods, int groupSize) {
return IntStream.range(0, foods.length)
.boxed()
.collect(Collectors.groupingBy(index -> index / groupSize))
.values()
.stream()
.map(indices -> indices
.stream()
.map(index -> foods[index])
.toArray(Food[]::new))
.toArray(Food[][]::new);
}
Effectively, partition
method allows to partition array into groups of arbitrary size groupSize
.
In case of the question, the desired result will be obtained by calling:
Food[][] result = partition(foods, 3);
Upvotes: 0
Reputation: 1879
What about this! You just iterate over the array and add three of them to a list and, after each three, add the list to another list, resetting the initial list.
ArrayList<ArrayList<Food>> result = new ArrayList<>();
ArrayList<Food> subArray = new ArrayList<>();
for (int i = 0; i < foods.length; i++) {
subArray.add(foods[i]);
if (i % 3 == 2) {
result.add(subArray);
subArray = new ArrayList<>();
}
}
Nice and simple. As Nicholas K suggested, I am using a List<List<Food>>
Upvotes: 3