General problem
I don't know how to divide a sorted list to smaller sorted lists but NOT in a manner like in Guava Lists.partition(list,size)
- so not to a smaller lists of specified size BUT to a fixed number of lists of similar size.
For example having a source list: 1,2,3,4 I want to have 3 lists as a results (the 3 is the fixed number of resulting lists). I should have the results List<List<Long>>
: ListOne: 1, ListTwo: 2, ListThree: 3,4 (keep in mind that sorting is kept).
When source list is smaller then number of target lists, then OK, I could get smaller number of lists. So whe a source list is 1,2 and I want to have 3 lists, the algorithm should return two lists: List1 1, List2: 2.
The size of the source list is unknown, but there are hundret of thousends of elements that have to be divided to 10 lists, becaouse then 10 threads are ready to do some more complicated operations with those elements.
The below algorithm is totally wrong, having 14 elements on source list and passing GRD_SIZE=10
it returns 7 lists of 2 elements. It should return GRD_SIZE=10
lists of similar sizes.
Propably I shouldn't also use the Guava Lists.partition method... But how to do this task ?
List<List<Long>> partitions = partition(sourceList, GRD_SIZE);
public static <T> List<List<T>> partition(List<T> ascSortedItems, int size)
{
int threadSize = (int) Math.ceil(
new BigDecimal(ascSortedItems.size()).divide(
new BigDecimal(
ascSortedItems.size() >= size ? size : ascSortedItems.size()
)
).doubleValue()
);
final AtomicInteger counter = new AtomicInteger(0);
return ascSortedItems.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / threadSize))
.values()
.stream()
.collect(Collectors.toList());
}