Distribute the list evenly into Java’s child lists
I want to distribute the list evenly into a given number of sub lists
SL1 -> {1,2,3,4} SL2 -> {5,6,7} SL3 -> {8,9,10}
Important: the contents contained in each list are irrelevant, that is, SL1 may have {1,5,7,10} The most important thing is that there are two lists of size 3 and one list of size 4
I tried several things, including iterables Partition, but it doesn't help
The only useful points I have put forward are:
public Iterable<List<Integer>> distributeEvenlyQueryListIntoLists(final LinkedList<Integer> bigList,final Integer numberOfSublists) { List<List<Integer>> result = new ArrayList<>(); // Creates as many lists as needed for (int i = 0; i < numberOfSublists; i++) { result.add(new ArrayList<>()); } while (bigList.iterator().hasNext()) { for (int i = 0; i < numberOfSublists; i++) { if (!bigList.iterator().hasNext()) { break; } result.get(i).add(bigList.poll()); } } return result; }
The passed biglist does not have to be a LinkedList, it can be any iteratable
I especially hate the first loop that creates a sublist
thank you!
Solution
Just distribute them in circular mode:
public <T> List<List<T>> partition(Iterable<T> iterable,int partitions){ List<List<T>> result = new ArrayList<>(partitions); for(int i = 0; i < partitions; i++) result.add(new ArrayList<>()); Iterator<T> iterator = iterable.iterator() for(int i = 0; iterator.hasNext(); i++) result.get(i % partitions).add(iterator.next()); return result; }
Examples to run with this Code:
List<String> l = Stream.iterate(0,i->i + 1).limit(25).map(i->Integer.toString(i)).collect(Collectors.toList()); System.out.println(partition(l,4).toString());
produce
The basic idea is to add an element to each list in the result set This ensures that the difference in the number of elements between the two lists does not exceed 1
As an alternative, you can use iterables The guavas implementation of partition requires a slightly different approach