public static List < PartitionDefinition > assignPartitions ( List < PartitionDefinition > partitions , int currentTask , int totalTasks ) { int esPartitions = partitions . size ( ) ; if ( totalTasks >= esPartitions ) { return ( currentTask >= esPartitions ? Collections . < PartitionDefinition > emptyList ( ) : Collections . singletonList ( partitions . get ( currentTask ) ) ) ; } else { int partitionsPerTask = esPartitions / totalTasks ; int remainder = esPartitions % totalTasks ; int partitionsPerCurrentTask = partitionsPerTask ; // spread the reminder against the tasks if ( currentTask < remainder ) { partitionsPerCurrentTask ++ ; } // find the offset inside the collection int offset = partitionsPerTask * currentTask ; if ( currentTask != 0 ) { offset += ( remainder > currentTask ? 1 : remainder ) ; } // common case if ( partitionsPerCurrentTask == 1 ) { return Collections . singletonList ( partitions . get ( offset ) ) ; } List < PartitionDefinition > pa = new ArrayList < PartitionDefinition > ( partitionsPerCurrentTask ) ; for ( int index = offset ; index < offset + partitionsPerCurrentTask ; index ++ ) { pa . add ( partitions . get ( index ) ) ; } return pa ; } }
expects currentTask to start from 0