Skip to content

Commit

Permalink
Add method listFilter()
Browse files Browse the repository at this point in the history
  • Loading branch information
mernst committed Oct 6, 2023
1 parent 9d54fb3 commit 4006930
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
- Require Java 11
- `StringsPlume`: add `rpad` that pads with an arbitrary character
- `CollectionsPlume`:
* add method `duplicates()`
* add methods `duplicates()` and `listFilter()`
* add an overload for `mapCapacity()`

## 1.8.1 (2023-06-02)
Expand Down
26 changes: 26 additions & 0 deletions src/main/java/org/plumelib/util/CollectionsPlume.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Predicate;
import org.checkerframework.checker.index.qual.NonNegative;
import org.checkerframework.checker.index.qual.Positive;
import org.checkerframework.checker.lock.qual.GuardSatisfied;
Expand Down Expand Up @@ -552,6 +553,31 @@ List<TO> transform(
return result;
}

/**
* Returns a new list containing only the elements for which the filter returns true. To modify
* the collection in place, use {@code Collection#removeIf}.
*
* <p>Using streams gives an equivalent list but is less efficient and more verbose:
*
* <pre>{@code
* coll.stream().filter(filter).collect(Collectors.toList());
* }</pre>
*
* @param <T> the type of elements
* @param coll a collection
* @param filter a predicate
* @return a new list with the elements for which the filter returns true
*/
public static <T> List<T> listFilter(Collection<T> coll, Predicate<? super T> filter) {
List<T> result = new ArrayList<>();
for (T elt : coll) {
if (filter.test(elt)) {
result.add(elt);
}
}
return result;
}

///////////////////////////////////////////////////////////////////////////
/// SortedSet
///
Expand Down
9 changes: 9 additions & 0 deletions src/test/java/org/plumelib/util/CollectionsPlumeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,15 @@ public void testTransform() {
assertEquals(out, CollectionsPlume.transform(in, Object::toString));
}

@Test
public void testListFilter() {
List<Integer> in = Arrays.asList(new Integer[] {1, 2, 3, 4, 5});
List<Integer> odd = Arrays.asList(new Integer[] {1, 3, 5});
List<Integer> even = Arrays.asList(new Integer[] {2, 4});
assertEquals(odd, CollectionsPlume.listFilter(in, i -> i % 2 == 1));
assertEquals(even, CollectionsPlume.listFilter(in, i -> i % 2 == 0));
}

@Test
public void testSortedSetEquals() {
TreeSet<Integer> s2 = new TreeSet<>(Arrays.asList(1, 2));
Expand Down

0 comments on commit 4006930

Please sign in to comment.