How to Split Array List into Equal Parts

How to split array list into equal parts?

This should give you all your parts :

int partitionSize = 1000;
List<List<Integer>> partitions = new LinkedList<List<Integer>>();
for (int i = 0; i < originalList.size(); i += partitionSize) {
partitions.add(originalList.subList(i,
Math.min(i + partitionSize, originalList.size())));
}

Split Java ArrayList into equal parts

It seems like you are mixing up the number of segments and the number of elements per segment. In your example, both are the same, so the result is correct, but in other cases it will not be. For instance, i1 is created as the number of elements per segment, with the number of segments being hard-coded as 5.0. Then, in the loop, you treat i1 as the number of segments, while the number of elements per segment is hard-coded as 5. Mistakes like this will be easier to spot if you use properly named variables, like numSegments or segmentSize instead of i1 or integer constants.

Also:

  • no need to wrap the sublists into new ArrayList
  • you can just count by increments according to the number of elements per sublist instead of using two counters, for the current sublist and the offset
  • you could use a ternary ... ? ... : ... instead of that if/else

How about this:

public static void main(String[] args) {
List<String> arrayList = new ArrayList<String>();
for (int i = 0; i < 23; i++) {
arrayList.add(String.valueOf(i));
}

int size = 5;
for (int start = 0; start < arrayList.size(); start += size) {
int end = Math.min(start + size, arrayList.size());
List<String> sublist = arrayList.subList(start, end);
System.out.println(sublist);
}
}

Here, size is the number of elements in each sublist. So instead of counting the segment of the list and increasing a second counter by 5 each time, you can just increase the first counter by five in the third argument of the for loop. Also, you can use the result of subList directly, without passing it to a constructor first. And you can get rid of the if-else by using min to determine the end index.

Output:

[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[10, 11, 12, 13, 14]
[15, 16, 17, 18, 19]
[20, 21, 22]

If instead of sublists with 5 elements you wanted five sublists, then use this (same result for the given example, but different for other list sizes):

int size = (int) Math.ceil(arrayList.size() / 5.0);

Java: how can I split an ArrayList in multiple small ArrayLists?

You can use subList(int fromIndex, int toIndex) to get a view of a portion of the original list.

From the API:

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

Example:

List<Integer> numbers = new ArrayList<Integer>(
Arrays.asList(5,3,1,2,9,5,0,7)
);

List<Integer> head = numbers.subList(0, 4);
List<Integer> tail = numbers.subList(4, 8);
System.out.println(head); // prints "[5, 3, 1, 2]"
System.out.println(tail); // prints "[9, 5, 0, 7]"

Collections.sort(head);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7]"

tail.add(-1);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7, -1]"

If you need these chopped lists to be NOT a view, then simply create a new List from the subList. Here's an example of putting a few of these things together:

// chops a list into non-view sublists of length L
static <T> List<List<T>> chopped(List<T> list, final int L) {
List<List<T>> parts = new ArrayList<List<T>>();
final int N = list.size();
for (int i = 0; i < N; i += L) {
parts.add(new ArrayList<T>(
list.subList(i, Math.min(N, i + L)))
);
}
return parts;
}

List<Integer> numbers = Collections.unmodifiableList(
Arrays.asList(5,3,1,2,9,5,0,7)
);
List<List<Integer>> parts = chopped(numbers, 3);
System.out.println(parts); // prints "[[5, 3, 1], [2, 9, 5], [0, 7]]"
parts.get(0).add(-1);
System.out.println(parts); // prints "[[5, 3, 1, -1], [2, 9, 5], [0, 7]]"
System.out.println(numbers); // prints "[5, 3, 1, 2, 9, 5, 0, 7]" (unmodified!)

Splitting a list into N parts of approximately equal length

This code is broken due to rounding errors. Do not use it!!!

assert len(chunkIt([1,2,3], 10)) == 10  # fails

Here's one that could work:

def chunkIt(seq, num):
avg = len(seq) / float(num)
out = []
last = 0.0

while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg

return out

Testing:

>>> chunkIt(range(10), 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
>>> chunkIt(range(11), 3)
[[0, 1, 2], [3, 4, 5, 6], [7, 8, 9, 10]]
>>> chunkIt(range(12), 3)
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

Split a list into equal parts?

The usual approach, when you’re fine with grouping all the larger pieces, is

const int total=/*…*/,pieces=/*…*/;
const int base=total/pieces,extra=total%pieces;

Then the first extra (perhaps 0) pieces have size base+1 and the (pieces-extra) others have size base.

split an integer list into 2 list of approximately the same length in Java

If you only need a view of the 2 parts of the initial List you can use List.subList(), but remember that this you made any change on the initial list, they will be seen on list1 and list2 as they are only views :

int middle = values.size() / 2;
List<Integer> list1 = values.subList(0, middle);
List<Integer> list2 = values.subList(middle, values.size());

To make news List with the same elements, you need to :

int middle = values.size() / 2;
List<Integer> list1 = new ArrayList<>(values.subList(0, middle));
List<Integer> list2 = new ArrayList<>(values.subList(middle, values.size()));

Split array into equal parts order by id using PHP

Sounds like you wanted something like this:

$array = [
[
'id' => 121,
'owner' => 'xa',
'name' => 'xjs',
],
[
'id' => 139,
'owner' => 'xa',
'name' => 'xjs',
],
[
'id' => 1456,
'owner' => 'xv',
'name' => 'bjs',
],
[
'id' => 1896,
'owner' => 'xb',
'name' => 'bjs',
],
[
'id' => 1963,
'owner' => 'xb',
'name' => 'bjs',
]
];

// custom function to compare which ID is greater
function customCompare($a, $b)
{
if ($a['id'] === $b['id']) {
return 0;
}

return ($a['id'] < $b['id']) ? -1 : 1;
}

// sort the whole array
usort($array, "customCompare");

// print the whole array as pairs,
// if there is an unpair number
// the last one will be a single member
print_r(array_chunk($array, 2));


Related Topics



Leave a reply



Submit