Returns the k least elements of the given iterable according to this ordering, in order from least to greatest. If there are fewer than k elements present, all will be included. The implementation does not necessarily use a stable sorting algorithm; when multiple elements
(Iterable<E> iterable, int k)
| 682 | |
| 683 | |
| 684 | public <E extends T> List<E> leastOf(Iterable<E> iterable, int k) { |
| 685 | if (iterable instanceof Collection) { |
| 686 | Collection<E> collection = (Collection<E>) iterable; |
| 687 | if (collection.size() <= 2L * k) { |
| 688 | // In this case, just dumping the collection to an array and sorting is |
| 689 | // faster than using the implementation for Iterator, which is |
| 690 | // specialized for k much smaller than n. |
| 691 | @SuppressWarnings("unchecked") // c only contains E's and doesn't escape |
| 692 | E[] array = (E[]) collection.toArray(); |
| 693 | Arrays.sort(array, this); |
| 694 | if (array.length > k) { |
| 695 | array = ObjectArrays.arraysCopyOf(array, k); |
| 696 | } |
| 697 | return Collections.unmodifiableList(Arrays.asList(array)); |
| 698 | } |
| 699 | } |
| 700 | return leastOf(iterable.iterator(), k); |
| 701 | } |
| 702 | |
| 703 | /** |
| 704 | * Returns the {@code k} least elements from the given iterator according to |
no test coverage detected