|
| 1 | + |
| 2 | +import java.util.ArrayList; |
| 3 | +import java.util.Collection; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.List; |
| 6 | +import java.util.function.BiFunction; |
| 7 | +import java.util.function.BinaryOperator; |
| 8 | +import java.util.function.Predicate; |
| 9 | +import java.util.function.UnaryOperator; |
| 10 | +import java.util.stream.Collectors; |
| 11 | +import java.util.stream.Stream; |
| 12 | + |
| 13 | +public class ListOps { |
| 14 | + |
| 15 | + private ListOps() { |
| 16 | + } |
| 17 | + |
| 18 | + public static <T> int length(final List<T> list) { |
| 19 | + return list.size(); |
| 20 | + } |
| 21 | + |
| 22 | + public static <T> List<T> reverse(final List<T> list) { |
| 23 | + List<T> result = new ArrayList(list); |
| 24 | + Collections.reverse(result); |
| 25 | + return result; |
| 26 | + } |
| 27 | + |
| 28 | + public static <T> List<T> map(final List<T> list, |
| 29 | + UnaryOperator<T> mapper) { |
| 30 | + return list.stream().map(mapper).collect(Collectors.toList()); |
| 31 | + } |
| 32 | + |
| 33 | + public static <T> List<T> filter(final List<T> list, |
| 34 | + Predicate<T> predicate) { |
| 35 | + return list.stream().filter(predicate).collect(Collectors.toList()); |
| 36 | + } |
| 37 | + |
| 38 | + public static <U, T> U reduce(final List<T> list, |
| 39 | + U identity, |
| 40 | + BiFunction<U, T, U> accumulator, |
| 41 | + BinaryOperator<U> combiner) { |
| 42 | + return list.stream().reduce(identity, accumulator, combiner); |
| 43 | + } |
| 44 | + |
| 45 | + public static <T> boolean append(final List<T> listTo, |
| 46 | + List<T> listFrom) { |
| 47 | + return listTo.addAll(listFrom); |
| 48 | + } |
| 49 | + |
| 50 | + public static <T> List<T> concat(final List<T>... lists) { |
| 51 | + return Stream.of(lists) |
| 52 | + .flatMap(Collection::stream) |
| 53 | + .collect(Collectors.toList()); |
| 54 | + } |
| 55 | + |
| 56 | +} |
0 commit comments