You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@commons.apache.org by "hextriclosan (via GitHub)" <gi...@apache.org> on 2026/08/03 12:06:26 UTC

[PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

hextriclosan opened a new pull request, #721:
URL: https://github.com/apache/commons-collections/pull/721

   Add an Iterator<List<E>> that generates the permutations of a collection in lexicographical order, complementing PermutationIterator, which uses the Steinhaus-Johnson-Trotter ordering.
   
   Elements are ordered by their natural ordering, or by a Comparator supplied to the two-argument constructor, which also allows permuting elements that do not implement Comparable. Each call to next() advances by the standard next-permutation step: locate the pivot, swap it with its successor, then reverse the descending tail. Equal elements are not distinguished, so an input with duplicates yields fewer than n! permutations. An empty collection yields exactly one empty list, as 0! = 1. remove() is unsupported.
   
   Comparator dispatch follows the java.util.TreeMap pattern of testing the comparator field for null on each comparison; benchmarking showed no measurable difference against normalizing null to Comparator.naturalOrder() in the constructor.
   
   Tests extend AbstractIteratorTest to cover the Iterator contract, and add cases for lexicographical exhaustivity, duplicate handling, custom and reverse comparators, non-Comparable elements, stream traversal, exhaustion, and equals/hashCode.
   
   <!--
     Licensed to the Apache Software Foundation (ASF) under one
     or more contributor license agreements.  See the NOTICE file
     distributed with this work for additional information
     regarding copyright ownership.  The ASF licenses this file
     to you under the Apache License, Version 2.0 (the
     "License"); you may not use this file except in compliance
     with the License.  You may obtain a copy of the License at
   
       https://www.apache.org/licenses/LICENSE-2.0
   
     Unless required by applicable law or agreed to in writing,
     software distributed under the License is distributed on an
     "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
     specific language governing permissions and limitations
     under the License.
   -->
   
   Thanks for your contribution to [Apache Commons](https://commons.apache.org/)! Your help is appreciated!
   
   Before you push a pull request, review this list:
   
   - [ ] Read the [contribution guidelines](CONTRIBUTING.md) for this project.
   - [ ] Read the [ASF Generative Tooling Guidance](https://www.apache.org/legal/generative-tooling.html) if you use Artificial Intelligence (AI).
   - [ ] I used AI to create any part of, or all of, this pull request. Which AI tool was used to create this pull request, and to what extent did it contribute? Claude for polishing documentation.
   - [ ] Run a successful build using the default [Maven](https://maven.apache.org/) goal with `mvn`; that's `mvn` on the command line by itself.
   - [ ] Write unit tests that match behavioral changes, where the tests fail if the changes to the runtime are not applied. This may not always be possible, but it is a best practice.
   - [ ] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
   - [ ] Each commit in the pull request should have a meaningful subject line and body. Note that a maintainer may squash commits during the merge process.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

Posted by "hextriclosan (via GitHub)" <gi...@apache.org>.
hextriclosan commented on code in PR #721:
URL: https://github.com/apache/commons-collections/pull/721#discussion_r3767892166


##########
src/main/java/org/apache/commons/collections4/iterators/LexicographicPermutationIterator.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.iterators;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+
+/**
+ * This iterator creates permutations of an input collection, using the
+ * lexicographical order.
+ * <p>
+ * The iterator might return fewer than n! permutations of the input collection,
+ * because duplicated permutations are skipped: equal elements are not
+ * distinguished from one another.
+ * The {@code remove()} operation is not supported, and will throw an
+ * {@code UnsupportedOperationException}.
+ * </p>
+ * <p>
+ * NOTE: in case an empty collection is provided, the iterator will
+ * return exactly one empty list as result, as 0! = 1.
+ * </p>
+ *
+ * @param <E>  the type of the objects being permuted
+ * @see PermutationIterator
+ * @since 4.6.0
+ */
+public class LexicographicPermutationIterator<E> implements Iterator<List<E>> {
+
+    /**
+     * The comparator used to define order of generation,
+     * or null if it uses the natural ordering.
+     */
+    private final Comparator<? super E> comparator;
+
+    /**
+     * Next permutation to return. When a permutation is requested
+     * this instance is provided and the next one is computed.
+     */
+    private List<E> nextPermutation;
+
+    /**
+     * Standard constructor for this class, using the natural ordering of the elements.
+     *
+     * @param collection  The collection to generate permutations for
+     * @throws NullPointerException if collection is null
+     */
+    public LexicographicPermutationIterator(final Collection<? extends E> collection) {
+        this(collection, null);
+    }
+
+    /**
+     * Constructs an instance using the given comparator to order the elements.
+     *
+     * @param collection  The collection to generate permutations for
+     * @param comparator  The comparator used to define the order of generation,
+     *                    or null to use the natural ordering of the elements
+     * @throws NullPointerException if collection is null
+     */
+    public LexicographicPermutationIterator(final Collection<? extends E> collection, final Comparator<? super E> comparator) {
+        Objects.requireNonNull(collection, "collection");
+        nextPermutation = new ArrayList<>(collection);
+        this.comparator = comparator;
+    }

Review Comment:
   The described behavior is real and the javadoc was actively misleading about it. I've pushed doc and test changes rather than the sort, and here's the reasoning.
   
   The truncation is intentional. This class is the iterator form of the classic next-permutation step: it starts wherever the input puts it and advances to the smallest arrangement greater than the current one, exactly as `std::next_permutation` does in C++. Sorted input is a precondition for enumerating the full set, in the same way sorted input is a precondition for `Collections.binarySearch`. That precondition simply wasn't documented.
   
   I'd rather not sort in the constructor, because sorting is not a neutral addition. It removes a capability that cannot be recovered:
   
   - Resuming. A caller that persisted the last arrangement it processed can construct an iterator from it and carry on. With a constructor sort there is no way to express "start here".
   - Splitting the work. The permutation space can be divided across threads or machines by handing each worker a different starting arrangement. Same problem.
   
   A caller who wants the complete set can always sort before constructing, and that is one line at the call site. A caller who wants to start partway through has no recourse if the constructor sorts. The asymmetry is what decides it for me: preserving the given order is strictly the more expressive of the two designs.
   
   There's also a ready alternative for callers who want all n! without thinking about order, namely `PermutationIterator`, which reaches every arrangement from any starting point because Steinhaus-Johnson-Trotter enumerates the whole group. The two classes are genuinely different tools, and I've added a note making the differences explicit so the @see link stops implying they're interchangeable.



##########
src/test/java/org/apache/commons/collections4/iterators/LexicographicPermutationIteratorTest.java:
##########
@@ -0,0 +1,343 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.iterators;
+
+import static java.util.Collections.emptyList;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Test class for LexicographicPermutationIterator.
+ */
+class LexicographicPermutationIteratorTest extends AbstractIteratorTest<List<Character>> {
+
+    /**
+     * A comparator that orders nothing, identified only by an id, used to check that
+     * equal comparators make equal iterators.
+     *
+     * @param <T> the type of the objects compared
+     */
+    private static final class CustomComparator<T> implements Comparator<T> {
+
+        private final int id;
+
+        CustomComparator(final int id) {
+            this.id = id;
+        }
+
+        @Override
+        public int compare(final T o1, final T o2) {
+            return 0;
+        }
+
+        @Override
+        public boolean equals(final Object o) {
+            if (this == o) {
+                return true;
+            }
+
+            if (o == null || getClass() != o.getClass()) {
+                return false;
+            }
+
+            final CustomComparator<?> cmp = (CustomComparator<?>) o;
+            return id == cmp.id;
+        }
+
+        @Override
+        public int hashCode() {
+            return id;
+        }
+    }
+
+    /**
+     * A value holder that deliberately does not implement {@link Comparable}, used to
+     * check that a supplied comparator is honored.
+     *
+     * @param <T> the type of the wrapped value
+     */
+    private static final class NonComparableObject<T> {
+
+        private final T value;
+
+        NonComparableObject(final T value) {
+            this.value = value;
+        }
+
+        @Override
+        public boolean equals(final Object o) {
+            if (this == o) {
+                return true;
+            }
+
+            if (o == null || getClass() != o.getClass()) {
+                return false;
+            }
+
+            final NonComparableObject<?> that = (NonComparableObject<?>) o;
+            return Objects.equals(value, that.value);
+        }
+
+        T getValue() {
+            return value;
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(value);
+        }
+    }
+
+    @SuppressWarnings("boxing") // OK in test code
+    protected Character[] testArray = { 'A', 'B', 'C' };
+
+    protected List<Character> testList;
+
+    @Override
+    public LexicographicPermutationIterator<Character> makeEmptyIterator() {
+        return new LexicographicPermutationIterator<>(new ArrayList<>());
+    }
+
+    @Override
+    public LexicographicPermutationIterator<Character> makeObject() {
+        return new LexicographicPermutationIterator<>(testList);
+    }
+
+    @BeforeEach
+    public void setUp() {
+        testList = new ArrayList<>();
+        testList.addAll(Arrays.asList(testArray));
+    }
+
+    @Override
+    public boolean supportsEmptyIterator() {
+        return false;
+    }
+
+    @Override
+    public boolean supportsRemove() {
+        return false;
+    }
+
+    @Test
+    void testCustomComparator() {
+        final Iterator<List<Character>> permutationIterator = new LexicographicPermutationIterator<>(Arrays.asList('C', 'B', 'A'),
+                Comparator.reverseOrder());
+

Review Comment:
   Good news on this one: the test already covers what you're after, and I can show it. I patched `compareElements` to ignore the comparator and ran the suite. `testCustomComparator` fails, and so does `testCustomComparatorWithNonComparableObjects`.                                                                                                                                 
                                                                                                                                                                                                                                                                                                                                                                                      
   The reason `['C','B','A']` works as input is that it's the maximum under natural ordering. An implementation that ignored the comparator would find no pivot, terminate after a single permutation, and fail on the second `assertTrue`. The test therefore separates "comparator honoured, 6 permutations in reverse-lexicographic order" from "comparator ignored, 1 permutation".                                                                                                                                                                        
   
   You're right that neither test exercised input unsorted under its own comparator. I've added `testUnsortedCollectionStartsAtGivenArrangementWithComparator` for exactly that, passing ['B','C','A'] with `reverseOrder()` and asserting the four permutations that follow it. Starting at the given arrangement is the intended contract here rather than a bug, for the reasons in  the other thread, and that test now pins it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

Posted by "garydgregory (via GitHub)" <gi...@apache.org>.
garydgregory commented on PR #721:
URL: https://github.com/apache/commons-collections/pull/721#issuecomment-5416930900

   Hello @hextriclosan, picking this low-hanging fruit: equals/hashCode aren't worth keeping for the first version of this class. Keeping the initial API surface small reduces maintenance, and the feature can be added later once there's a clear use case without worrying about backward compatibility. As you noted, other iterators don't support it, so adding it here would be inconsistent and invite questions about why we don't implement it everywhere, which we shouldn't take on.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #721:
URL: https://github.com/apache/commons-collections/pull/721#discussion_r3767554531


##########
src/test/java/org/apache/commons/collections4/iterators/LexicographicPermutationIteratorTest.java:
##########
@@ -0,0 +1,343 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.iterators;
+
+import static java.util.Collections.emptyList;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Test class for LexicographicPermutationIterator.
+ */
+class LexicographicPermutationIteratorTest extends AbstractIteratorTest<List<Character>> {
+
+    /**
+     * A comparator that orders nothing, identified only by an id, used to check that
+     * equal comparators make equal iterators.
+     *
+     * @param <T> the type of the objects compared
+     */
+    private static final class CustomComparator<T> implements Comparator<T> {
+
+        private final int id;
+
+        CustomComparator(final int id) {
+            this.id = id;
+        }
+
+        @Override
+        public int compare(final T o1, final T o2) {
+            return 0;
+        }
+
+        @Override
+        public boolean equals(final Object o) {
+            if (this == o) {
+                return true;
+            }
+
+            if (o == null || getClass() != o.getClass()) {
+                return false;
+            }
+
+            final CustomComparator<?> cmp = (CustomComparator<?>) o;
+            return id == cmp.id;
+        }
+
+        @Override
+        public int hashCode() {
+            return id;
+        }
+    }
+
+    /**
+     * A value holder that deliberately does not implement {@link Comparable}, used to
+     * check that a supplied comparator is honored.
+     *
+     * @param <T> the type of the wrapped value
+     */
+    private static final class NonComparableObject<T> {
+
+        private final T value;
+
+        NonComparableObject(final T value) {
+            this.value = value;
+        }
+
+        @Override
+        public boolean equals(final Object o) {
+            if (this == o) {
+                return true;
+            }
+
+            if (o == null || getClass() != o.getClass()) {
+                return false;
+            }
+
+            final NonComparableObject<?> that = (NonComparableObject<?>) o;
+            return Objects.equals(value, that.value);
+        }
+
+        T getValue() {
+            return value;
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(value);
+        }
+    }
+
+    @SuppressWarnings("boxing") // OK in test code
+    protected Character[] testArray = { 'A', 'B', 'C' };
+
+    protected List<Character> testList;
+
+    @Override
+    public LexicographicPermutationIterator<Character> makeEmptyIterator() {
+        return new LexicographicPermutationIterator<>(new ArrayList<>());
+    }
+
+    @Override
+    public LexicographicPermutationIterator<Character> makeObject() {
+        return new LexicographicPermutationIterator<>(testList);
+    }
+
+    @BeforeEach
+    public void setUp() {
+        testList = new ArrayList<>();
+        testList.addAll(Arrays.asList(testArray));
+    }
+
+    @Override
+    public boolean supportsEmptyIterator() {
+        return false;
+    }
+
+    @Override
+    public boolean supportsRemove() {
+        return false;
+    }
+
+    @Test
+    void testCustomComparator() {
+        final Iterator<List<Character>> permutationIterator = new LexicographicPermutationIterator<>(Arrays.asList('C', 'B', 'A'),
+                Comparator.reverseOrder());
+

Review Comment:
   This test currently passes a list that is already sorted for `Comparator.reverseOrder()`, so it doesn’t verify that the iterator actually orders the input according to the comparator (as described). Using an unsorted input here would catch the case where the implementation starts from the collection’s iteration order and misses earlier lexicographic permutations.
   
   This issue also appears on line 265 of the same file.



##########
src/main/java/org/apache/commons/collections4/iterators/LexicographicPermutationIterator.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.iterators;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+
+/**
+ * This iterator creates permutations of an input collection, using the
+ * lexicographical order.
+ * <p>
+ * The iterator might return fewer than n! permutations of the input collection,
+ * because duplicated permutations are skipped: equal elements are not
+ * distinguished from one another.
+ * The {@code remove()} operation is not supported, and will throw an
+ * {@code UnsupportedOperationException}.
+ * </p>
+ * <p>
+ * NOTE: in case an empty collection is provided, the iterator will
+ * return exactly one empty list as result, as 0! = 1.
+ * </p>
+ *
+ * @param <E>  the type of the objects being permuted
+ * @see PermutationIterator
+ * @since 4.6.0
+ */
+public class LexicographicPermutationIterator<E> implements Iterator<List<E>> {
+
+    /**
+     * The comparator used to define order of generation,
+     * or null if it uses the natural ordering.
+     */
+    private final Comparator<? super E> comparator;
+
+    /**
+     * Next permutation to return. When a permutation is requested
+     * this instance is provided and the next one is computed.
+     */
+    private List<E> nextPermutation;
+
+    /**
+     * Standard constructor for this class, using the natural ordering of the elements.
+     *
+     * @param collection  The collection to generate permutations for
+     * @throws NullPointerException if collection is null
+     */
+    public LexicographicPermutationIterator(final Collection<? extends E> collection) {
+        this(collection, null);
+    }
+
+    /**
+     * Constructs an instance using the given comparator to order the elements.
+     *
+     * @param collection  The collection to generate permutations for
+     * @param comparator  The comparator used to define the order of generation,
+     *                    or null to use the natural ordering of the elements
+     * @throws NullPointerException if collection is null
+     */
+    public LexicographicPermutationIterator(final Collection<? extends E> collection, final Comparator<? super E> comparator) {
+        Objects.requireNonNull(collection, "collection");
+        nextPermutation = new ArrayList<>(collection);
+        this.comparator = comparator;
+    }

Review Comment:
   Lexicographic permutation generation only produces the full ordered permutation set if the iterator starts from the minimal permutation under the chosen ordering. Currently the constructor preserves the collection’s iteration order, so an unsorted input will skip all permutations that come before it (and may even yield only a suffix of permutations). Sort the initial `nextPermutation` using the supplied comparator (or natural ordering) so iteration always starts at the first lexicographic permutation.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

Posted by "hextriclosan (via GitHub)" <gi...@apache.org>.
hextriclosan commented on code in PR #721:
URL: https://github.com/apache/commons-collections/pull/721#discussion_r3803089849


##########
src/main/java/org/apache/commons/collections4/iterators/LexicographicPermutationIterator.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.iterators;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+
+/**
+ * This iterator creates permutations of an input collection, using the
+ * lexicographical order.
+ * <p>
+ * Iteration starts at the arrangement in which the elements are given, and each
+ * call to {@code next()} advances to the smallest arrangement greater than the
+ * current one. Iteration therefore ends at the largest arrangement, and the ones
+ * preceding the given arrangement are never returned: only a collection already
+ * sorted according to the ordering in use yields the complete set of
+ * permutations. Callers wanting the complete set must sort the collection
+ * beforehand, just as callers of
+ * {@link java.util.Collections#binarySearch(java.util.List, Object) binarySearch}
+ * must. Callers wanting to enumerate one part of the set, to resume from a
+ * previously reached arrangement or to split the work, may start anywhere.
+ * </p>
+ * <p>
+ * The starting arrangement is the iteration order of the given collection, so
+ * collections whose iteration order is unspecified, such as {@link java.util.HashSet},
+ * make poor input: which permutations are returned is then unspecified too.
+ * </p>
+ * <p>
+ * The iterator might return fewer than n! permutations of the input collection,
+ * either because the collection was not sorted according to the ordering in use,
+ * as described above, or because duplicated permutations are skipped: equal
+ * elements are not distinguished from one another.
+ * The {@code remove()} operation is not supported, and will throw an
+ * {@code UnsupportedOperationException}.
+ * </p>
+ * <p>
+ * NOTE: in case an empty collection is provided, the iterator will
+ * return exactly one empty list as result, as 0! = 1.
+ * </p>
+ * <p>
+ * NOTE: {@link PermutationIterator} differs on both counts. It returns exactly n!
+ * permutations whatever the order of the input collection. The two iterators are
+ * therefore not interchangeable.
+ * </p>
+ *
+ * @param <E>  the type of the objects being permuted
+ * @see PermutationIterator
+ * @since 4.7.0
+ */
+public class LexicographicPermutationIterator<E> implements Iterator<List<E>> {
+
+    /**
+     * The comparator used to define order of generation,
+     * or null if it uses the natural ordering.
+     */
+    private final Comparator<? super E> comparator;
+
+    /**
+     * Next permutation to return. When a permutation is requested
+     * this instance is provided and the next one is computed.
+     */
+    private List<E> nextPermutation;
+
+    /**
+     * Standard constructor for this class, using the natural ordering of the elements.
+     * <p>
+     * Iteration starts at the arrangement in which the collection iterates its
+     * elements; sort the collection first to obtain the complete set of permutations.
+     * </p>
+     *
+     * @param collection  The collection to generate permutations for
+     * @throws NullPointerException if collection is null
+     */
+    public LexicographicPermutationIterator(final Collection<? extends E> collection) {
+        this(collection, null);
+    }
+
+    /**
+     * Constructs an instance using the given comparator to order the elements.
+     * <p>
+     * Iteration starts at the arrangement in which the collection iterates its
+     * elements; sort the collection with the same comparator first to obtain the
+     * complete set of permutations.
+     * </p>
+     *
+     * @param collection  The collection to generate permutations for
+     * @param comparator  The comparator used to define the order of generation,
+     *                    or null to use the natural ordering of the elements
+     * @throws NullPointerException if collection is null
+     */
+    public LexicographicPermutationIterator(final Collection<? extends E> collection, final Comparator<? super E> comparator) {
+        Objects.requireNonNull(collection, "collection");
+        nextPermutation = new ArrayList<>(collection);
+        this.comparator = comparator;
+    }
+
+    /**
+     * Indicates if there are more permutation available.

Review Comment:
   Fixed, thanks



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

Posted by "hextriclosan (via GitHub)" <gi...@apache.org>.
hextriclosan commented on PR #721:
URL: https://github.com/apache/commons-collections/pull/721#issuecomment-5317927367

   Hello @garydgregory,
   
   Thank you for the review and the advice.
   
   What changed:
     - Javadoc polished
     - Missing tests added
     - `next()` now returns a defensive copy, covered by new tests
   
   Two points where I would value your opinion:
   
   **1. `next()` returning a copy.**
   The copy is taken before the iterator advances, so the caller's list is detached regardless of what the successor computation does:
   - pros: callers may modify the returned list freely, and the guarantee no longer depends on internal ordering.
   - cons: one extra list allocation per permutation, and since `PermutationIterator` hands out its internal list, the two classes now differ internally.
   
   **2. Are equals/hashCode worth keeping?**
   They looked reasonable to me, but I have doubts:
   
   - No other iterator in o.a.c.c.iterators overrides them, and neither do the JDK iterators. Identity semantics seem to be the convention.
   - The hash code changes as the iterator advances, so an instance used as a HashMap key becomes unfindable after the first next().
   - Two exhausted iterators built from different collections compare equal, since equality is defined on the comparator and the next permutation (see `testEqualsAndHashCodeForExhaustedIterators`). Defensible, as both will emit nothing further, but surprising.
   
   Thanks again for taking the time.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

Posted by "hextriclosan (via GitHub)" <gi...@apache.org>.
hextriclosan commented on PR #721:
URL: https://github.com/apache/commons-collections/pull/721#issuecomment-5269749462

   Fair point, the C++ reference doesn't belong here. Let me restate it in terms of this library.
   
   Within Java Collections, `Collections.binarySearch` is the pattern: "The list must be sorted into ascending order according to the natural ordering of its elements... If it is not sorted, the results are undefined." The JDK documents the precondition and trusts the caller rather than sorting defensively. 
   
   Within Commons Collections, `CollatingIterator` in this same package does the same thing. It provides an ordered iteration over a collection of ordered iterators, states that in the first line of its javadoc, and never sorts its inputs. Unordered input gives unordered output. That's the precedent I should have cited from the start.                                      
                                                                                                                                                                                                                                                                                                                                                                                      
   The substantive reason is about what each design permits. A caller who wants the complete set can sort before constructing, one line at the call site. A caller who wants to resume from a previously reached arrangement, or to split the permutation space across workers by giving each a different starting point, has no recourse if the constructor sorts. Sorting is not recoverable from outside the class, so the version that preserves the given order is strictly the more capable of the two.
   
   What I've pushed documents the precondition, since the javadoc previously contradicted it, and adds tests pinning it for both natural ordering and a supplied comparator.
   
   If you'd still rather the complete set be the default, I'd suggest a static factory such as `overAll(collection)` that sorts a copy, keeping the start-anywhere behavior available on the constructor.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

Posted by "garydgregory (via GitHub)" <gi...@apache.org>.
garydgregory commented on PR #721:
URL: https://github.com/apache/commons-collections/pull/721#issuecomment-5268536664

   Hello @hextriclosan 
   
   Thank you for the PR.
   
   Please review each Copiot comment and address them in comments here, in the code, or both. If you update the code, do make sure new unit tests cover all execution paths.
   
   TY!
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

Posted by "hextriclosan (via GitHub)" <gi...@apache.org>.
hextriclosan commented on PR #721:
URL: https://github.com/apache/commons-collections/pull/721#issuecomment-5269221038

   @garydgregory,
   
   I've pushed doc and test changes. The implementation is unchanged, my reasoning is in the inline replies.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

Posted by "hextriclosan (via GitHub)" <gi...@apache.org>.
hextriclosan commented on code in PR #721:
URL: https://github.com/apache/commons-collections/pull/721#discussion_r3803105794


##########
src/main/java/org/apache/commons/collections4/iterators/LexicographicPermutationIterator.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.iterators;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+
+/**
+ * This iterator creates permutations of an input collection, using the
+ * lexicographical order.
+ * <p>
+ * Iteration starts at the arrangement in which the elements are given, and each
+ * call to {@code next()} advances to the smallest arrangement greater than the
+ * current one. Iteration therefore ends at the largest arrangement, and the ones
+ * preceding the given arrangement are never returned: only a collection already
+ * sorted according to the ordering in use yields the complete set of
+ * permutations. Callers wanting the complete set must sort the collection
+ * beforehand, just as callers of
+ * {@link java.util.Collections#binarySearch(java.util.List, Object) binarySearch}
+ * must. Callers wanting to enumerate one part of the set, to resume from a
+ * previously reached arrangement or to split the work, may start anywhere.
+ * </p>
+ * <p>
+ * The starting arrangement is the iteration order of the given collection, so
+ * collections whose iteration order is unspecified, such as {@link java.util.HashSet},
+ * make poor input: which permutations are returned is then unspecified too.
+ * </p>
+ * <p>
+ * The iterator might return fewer than n! permutations of the input collection,
+ * either because the collection was not sorted according to the ordering in use,
+ * as described above, or because duplicated permutations are skipped: equal
+ * elements are not distinguished from one another.
+ * The {@code remove()} operation is not supported, and will throw an
+ * {@code UnsupportedOperationException}.
+ * </p>
+ * <p>
+ * NOTE: in case an empty collection is provided, the iterator will
+ * return exactly one empty list as result, as 0! = 1.
+ * </p>
+ * <p>
+ * NOTE: {@link PermutationIterator} differs on both counts. It returns exactly n!
+ * permutations whatever the order of the input collection. The two iterators are
+ * therefore not interchangeable.
+ * </p>
+ *
+ * @param <E>  the type of the objects being permuted
+ * @see PermutationIterator
+ * @since 4.7.0
+ */
+public class LexicographicPermutationIterator<E> implements Iterator<List<E>> {
+
+    /**
+     * The comparator used to define order of generation,
+     * or null if it uses the natural ordering.
+     */
+    private final Comparator<? super E> comparator;
+
+    /**
+     * Next permutation to return. When a permutation is requested
+     * this instance is provided and the next one is computed.
+     */
+    private List<E> nextPermutation;
+
+    /**
+     * Standard constructor for this class, using the natural ordering of the elements.
+     * <p>
+     * Iteration starts at the arrangement in which the collection iterates its
+     * elements; sort the collection first to obtain the complete set of permutations.
+     * </p>
+     *
+     * @param collection  The collection to generate permutations for
+     * @throws NullPointerException if collection is null
+     */
+    public LexicographicPermutationIterator(final Collection<? extends E> collection) {
+        this(collection, null);
+    }
+
+    /**
+     * Constructs an instance using the given comparator to order the elements.
+     * <p>
+     * Iteration starts at the arrangement in which the collection iterates its
+     * elements; sort the collection with the same comparator first to obtain the
+     * complete set of permutations.
+     * </p>
+     *
+     * @param collection  The collection to generate permutations for
+     * @param comparator  The comparator used to define the order of generation,
+     *                    or null to use the natural ordering of the elements
+     * @throws NullPointerException if collection is null
+     */
+    public LexicographicPermutationIterator(final Collection<? extends E> collection, final Comparator<? super E> comparator) {
+        Objects.requireNonNull(collection, "collection");
+        nextPermutation = new ArrayList<>(collection);
+        this.comparator = comparator;
+    }
+
+    /**
+     * Indicates if there are more permutation available.
+     *
+     * @return true if there are more permutations, otherwise false
+     */
+    @Override
+    public boolean hasNext() {
+        return nextPermutation != null;
+    }
+
+    /**
+     * Returns the next permutation of the input collection.
+     *
+     * @return A list of the permutator's elements representing a permutation
+     * @throws NoSuchElementException if there are no more permutations
+     * @throws ClassCastException if no comparator was supplied and the elements are
+     *         not mutually {@link Comparable}
+     */
+    @Override
+    public List<E> next() {

Review Comment:
   Switched to a defensive copy. Details in a separate comment.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

Posted by "hextriclosan (via GitHub)" <gi...@apache.org>.
hextriclosan commented on PR #721:
URL: https://github.com/apache/commons-collections/pull/721#issuecomment-5418003104

   > Hello @hextriclosan, picking this low-hanging fruit: equals/hashCode aren't worth keeping for the first version of this class. Keeping the initial API surface small reduces maintenance, and the feature can be added later once there's a clear use case without worrying about backward compatibility. As you noted, other iterators don't support it, so adding it here would be inconsistent and invite questions about why we don't implement it everywhere, which we shouldn't take on.
   
   Hello @garydgregory,
   I've removed equals/hashCode


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

Posted by "hextriclosan (via GitHub)" <gi...@apache.org>.
hextriclosan commented on PR #721:
URL: https://github.com/apache/commons-collections/pull/721#issuecomment-5478524704

   Hello @garydgregory, pushed the fixes for your comments, build is green. Could you take another look when you get a chance?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

Posted by "garydgregory (via GitHub)" <gi...@apache.org>.
garydgregory commented on PR #721:
URL: https://github.com/apache/commons-collections/pull/721#issuecomment-5269611853

   C++? That's completely irrelevant. The code should only care about (1) the specifics of Commons Collections, and (2) how we extend Java Collections. Whatever happens in a C++ library doesn't come into play. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [COLLECTIONS-897] Add LexicographicPermutationIterator [commons-collections]

Posted by "garydgregory (via GitHub)" <gi...@apache.org>.
garydgregory commented on code in PR #721:
URL: https://github.com/apache/commons-collections/pull/721#discussion_r3793703054


##########
src/main/java/org/apache/commons/collections4/iterators/LexicographicPermutationIterator.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.iterators;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+
+/**
+ * This iterator creates permutations of an input collection, using the
+ * lexicographical order.
+ * <p>
+ * Iteration starts at the arrangement in which the elements are given, and each
+ * call to {@code next()} advances to the smallest arrangement greater than the
+ * current one. Iteration therefore ends at the largest arrangement, and the ones
+ * preceding the given arrangement are never returned: only a collection already
+ * sorted according to the ordering in use yields the complete set of
+ * permutations. Callers wanting the complete set must sort the collection
+ * beforehand, just as callers of
+ * {@link java.util.Collections#binarySearch(java.util.List, Object) binarySearch}
+ * must. Callers wanting to enumerate one part of the set, to resume from a
+ * previously reached arrangement or to split the work, may start anywhere.
+ * </p>
+ * <p>
+ * The starting arrangement is the iteration order of the given collection, so
+ * collections whose iteration order is unspecified, such as {@link java.util.HashSet},
+ * make poor input: which permutations are returned is then unspecified too.
+ * </p>
+ * <p>
+ * The iterator might return fewer than n! permutations of the input collection,
+ * either because the collection was not sorted according to the ordering in use,
+ * as described above, or because duplicated permutations are skipped: equal
+ * elements are not distinguished from one another.
+ * The {@code remove()} operation is not supported, and will throw an
+ * {@code UnsupportedOperationException}.
+ * </p>
+ * <p>
+ * NOTE: in case an empty collection is provided, the iterator will
+ * return exactly one empty list as result, as 0! = 1.
+ * </p>
+ * <p>
+ * NOTE: {@link PermutationIterator} differs on both counts. It returns exactly n!
+ * permutations whatever the order of the input collection. The two iterators are
+ * therefore not interchangeable.
+ * </p>
+ *
+ * @param <E>  the type of the objects being permuted
+ * @see PermutationIterator
+ * @since 4.7.0
+ */
+public class LexicographicPermutationIterator<E> implements Iterator<List<E>> {
+
+    /**
+     * The comparator used to define order of generation,
+     * or null if it uses the natural ordering.
+     */
+    private final Comparator<? super E> comparator;
+
+    /**
+     * Next permutation to return. When a permutation is requested
+     * this instance is provided and the next one is computed.
+     */
+    private List<E> nextPermutation;
+
+    /**
+     * Standard constructor for this class, using the natural ordering of the elements.
+     * <p>
+     * Iteration starts at the arrangement in which the collection iterates its
+     * elements; sort the collection first to obtain the complete set of permutations.
+     * </p>
+     *
+     * @param collection  The collection to generate permutations for
+     * @throws NullPointerException if collection is null
+     */
+    public LexicographicPermutationIterator(final Collection<? extends E> collection) {
+        this(collection, null);
+    }
+
+    /**
+     * Constructs an instance using the given comparator to order the elements.
+     * <p>
+     * Iteration starts at the arrangement in which the collection iterates its
+     * elements; sort the collection with the same comparator first to obtain the
+     * complete set of permutations.
+     * </p>
+     *
+     * @param collection  The collection to generate permutations for
+     * @param comparator  The comparator used to define the order of generation,
+     *                    or null to use the natural ordering of the elements
+     * @throws NullPointerException if collection is null
+     */
+    public LexicographicPermutationIterator(final Collection<? extends E> collection, final Comparator<? super E> comparator) {
+        Objects.requireNonNull(collection, "collection");
+        nextPermutation = new ArrayList<>(collection);
+        this.comparator = comparator;
+    }
+
+    /**
+     * Indicates if there are more permutation available.
+     *
+     * @return true if there are more permutations, otherwise false
+     */
+    @Override
+    public boolean hasNext() {
+        return nextPermutation != null;
+    }
+
+    /**
+     * Returns the next permutation of the input collection.
+     *
+     * @return A list of the permutator's elements representing a permutation
+     * @throws NoSuchElementException if there are no more permutations
+     * @throws ClassCastException if no comparator was supplied and the elements are
+     *         not mutually {@link Comparable}
+     */
+    @Override
+    public List<E> next() {

Review Comment:
   The method returns the internal List<E> reference that was used for the previous step. `PermutationIterator` does the same, so the behavior is consistent with the existing code base, but it means callers receive a mutable list that is no longer referenced internally after the call. Would a defensive copy or unmodifiable view would be safer?
   
   Alternatively, the Javadoc could state that the returned `List` is mutable and should be treated as read-only.
   



##########
src/main/java/org/apache/commons/collections4/iterators/LexicographicPermutationIterator.java:
##########
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.collections4.iterators;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+
+/**
+ * This iterator creates permutations of an input collection, using the
+ * lexicographical order.
+ * <p>
+ * Iteration starts at the arrangement in which the elements are given, and each
+ * call to {@code next()} advances to the smallest arrangement greater than the
+ * current one. Iteration therefore ends at the largest arrangement, and the ones
+ * preceding the given arrangement are never returned: only a collection already
+ * sorted according to the ordering in use yields the complete set of
+ * permutations. Callers wanting the complete set must sort the collection
+ * beforehand, just as callers of
+ * {@link java.util.Collections#binarySearch(java.util.List, Object) binarySearch}
+ * must. Callers wanting to enumerate one part of the set, to resume from a
+ * previously reached arrangement or to split the work, may start anywhere.
+ * </p>
+ * <p>
+ * The starting arrangement is the iteration order of the given collection, so
+ * collections whose iteration order is unspecified, such as {@link java.util.HashSet},
+ * make poor input: which permutations are returned is then unspecified too.
+ * </p>
+ * <p>
+ * The iterator might return fewer than n! permutations of the input collection,
+ * either because the collection was not sorted according to the ordering in use,
+ * as described above, or because duplicated permutations are skipped: equal
+ * elements are not distinguished from one another.
+ * The {@code remove()} operation is not supported, and will throw an
+ * {@code UnsupportedOperationException}.
+ * </p>
+ * <p>
+ * NOTE: in case an empty collection is provided, the iterator will
+ * return exactly one empty list as result, as 0! = 1.
+ * </p>
+ * <p>
+ * NOTE: {@link PermutationIterator} differs on both counts. It returns exactly n!
+ * permutations whatever the order of the input collection. The two iterators are
+ * therefore not interchangeable.
+ * </p>
+ *
+ * @param <E>  the type of the objects being permuted
+ * @see PermutationIterator
+ * @since 4.7.0
+ */
+public class LexicographicPermutationIterator<E> implements Iterator<List<E>> {
+
+    /**
+     * The comparator used to define order of generation,
+     * or null if it uses the natural ordering.
+     */
+    private final Comparator<? super E> comparator;
+
+    /**
+     * Next permutation to return. When a permutation is requested
+     * this instance is provided and the next one is computed.
+     */
+    private List<E> nextPermutation;
+
+    /**
+     * Standard constructor for this class, using the natural ordering of the elements.
+     * <p>
+     * Iteration starts at the arrangement in which the collection iterates its
+     * elements; sort the collection first to obtain the complete set of permutations.
+     * </p>
+     *
+     * @param collection  The collection to generate permutations for
+     * @throws NullPointerException if collection is null
+     */
+    public LexicographicPermutationIterator(final Collection<? extends E> collection) {
+        this(collection, null);
+    }
+
+    /**
+     * Constructs an instance using the given comparator to order the elements.
+     * <p>
+     * Iteration starts at the arrangement in which the collection iterates its
+     * elements; sort the collection with the same comparator first to obtain the
+     * complete set of permutations.
+     * </p>
+     *
+     * @param collection  The collection to generate permutations for
+     * @param comparator  The comparator used to define the order of generation,
+     *                    or null to use the natural ordering of the elements
+     * @throws NullPointerException if collection is null
+     */
+    public LexicographicPermutationIterator(final Collection<? extends E> collection, final Comparator<? super E> comparator) {
+        Objects.requireNonNull(collection, "collection");
+        nextPermutation = new ArrayList<>(collection);
+        this.comparator = comparator;
+    }
+
+    /**
+     * Indicates if there are more permutation available.

Review Comment:
   ```suggestion
        * Indicates if there are more permutations available.
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@commons.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org