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)
| 666 | * @since 8.0 |
| 667 | */ |
| 668 | public <E extends T> List<E> leastOf(Iterable<E> iterable, int k) { |
| 669 | if (iterable instanceof Collection) { |
| 670 | Collection<E> collection = (Collection<E>) iterable; |
| 671 | if (collection.size() <= 2L * k) { |
| 672 | // In this case, just dumping the collection to an array and sorting is |
| 673 | // faster than using the implementation for Iterator, which is |
| 674 | // specialized for k much smaller than n. |
| 675 | |
| 676 | @SuppressWarnings("unchecked") // c only contains E's and doesn't escape |
| 677 | E[] array = (E[]) collection.toArray(); |
| 678 | Arrays.sort(array, this); |
| 679 | if (array.length > k) { |
| 680 | array = ObjectArrays.arraysCopyOf(array, k); |
| 681 | } |
| 682 | return Collections.unmodifiableList(Arrays.asList(array)); |
| 683 | } |
| 684 | } |
| 685 | return leastOf(iterable.iterator(), k); |
| 686 | } |
| 687 | |
| 688 | /** |
| 689 | * Returns the {@code k} least elements from the given iterator according to |
no test coverage detected