Utility methods for List.
| 34 | * Utility methods for {@link List}. |
| 35 | */ |
| 36 | public final class Lists { |
| 37 | |
| 38 | private Lists() { |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Applies a mapper function on a given collection and returns |
| 43 | * the results as a list. The resulting list is unmodifiable. |
| 44 | */ |
| 45 | public static <T, R> List<R> map(Collection<? extends T> c, |
| 46 | Function<T, R> mapper) { |
| 47 | return c.isEmpty() ? List.of() : c.stream().map(mapper).toList(); |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Tests the elements in a given collection and returns a list of elements |
| 52 | * that can pass the test. The resulting list is unmodifiable. |
| 53 | */ |
| 54 | public static <T> List<T> filter(Collection<T> c, |
| 55 | Predicate<? super T> predicate) { |
| 56 | List<T> result = c.stream().filter(predicate).toList(); |
| 57 | return result.isEmpty() ? List.of() : result; |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Converts an iterable object to a list. |
| 62 | */ |
| 63 | public static <T> List<T> asList(Iterable<T> iterable) { |
| 64 | return StreamSupport.stream(iterable.spliterator(), false).toList(); |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * Concatenates two lists and removes duplicate items in the resulting list. |
| 69 | */ |
| 70 | public static <T> List<T> concatDistinct( |
| 71 | List<? extends T> list1, List<? extends T> list2) { |
| 72 | Set<T> set = new LinkedHashSet<>(list1); |
| 73 | set.addAll(list2); |
| 74 | return List.copyOf(set); |
| 75 | } |
| 76 | } |
nothing calls this directly
no outgoing calls
no test coverage detected