From 9ec08698c8277db7f9d45438067c4984a060ea82 Mon Sep 17 00:00:00 2001 From: "Gregory.Shrago" Date: Tue, 7 Nov 2017 04:11:26 +0300 Subject: [PATCH] introduce sorted(Comparator) --- .../util/containers/TreeTraverserTest.java | 6 ++++++ .../com/intellij/util/containers/JBIterable.java | 15 +++++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/platform/platform-tests/testSrc/com/intellij/util/containers/TreeTraverserTest.java b/platform/platform-tests/testSrc/com/intellij/util/containers/TreeTraverserTest.java index 06b17c4c3096..868d2e1cd867 100644 --- a/platform/platform-tests/testSrc/com/intellij/util/containers/TreeTraverserTest.java +++ b/platform/platform-tests/testSrc/com/intellij/util/containers/TreeTraverserTest.java @@ -478,6 +478,12 @@ public class TreeTraverserTest extends TestCase { assertEquals(Arrays.asList(1, 2, 3, 4, 5), uniqueMod5.toList()); // same results again } + public void testSorted() { + JBIterable it1 = JBIterable.generate(1, INCREMENT).take(30); + JBIterable it2 = JBIterable.generate(30, o -> o - 1).take(30).sorted(Integer::compareTo); + assertEquals(it1.toList(), it2.unique().toList()); + } + // TreeTraversal ---------------------------------------------- @NotNull diff --git a/platform/util/src/com/intellij/util/containers/JBIterable.java b/platform/util/src/com/intellij/util/containers/JBIterable.java index d8d4a4faed5d..530f3f254f70 100644 --- a/platform/util/src/com/intellij/util/containers/JBIterable.java +++ b/platform/util/src/com/intellij/util/containers/JBIterable.java @@ -844,15 +844,26 @@ public abstract class JBIterable implements Iterable { } /** - * Collects all items into an {@link ArrayList} and returns them as the new {@code JBIterable}. + * Collects all items into an {@link ArrayList} and returns it wrapped in a new {@code JBIterable}. * @see JBIterable#collect(Collection) */ @NotNull public final JBIterable collect() { - if (content instanceof ArrayList) return this; + if (content instanceof Collection) return this; return collect(ContainerUtilRt.newArrayList()); } + /** + * Collects all items into an {@link ArrayList}, sorts it and returns it wrapped in a new {@code JBIterable}. + * @see JBIterable#collect(Collection) + */ + @NotNull + public final JBIterable sorted(@NotNull Comparator comparator) { + ArrayList list = addAllTo(ContainerUtilRt.newArrayList()); + Collections.sort(list, comparator); + return from(list); + } + /** * Returns a {@code List} containing all the elements from this iterable in * proper sequence.