Stream的抽象

152 阅读1分钟

StreamUtil

public class StreamUtil {
    public StreamUtil() {
    }
    // 转换对象
    public static <E, R> List<R> map(Collection<E> list, Function<E, R> function) {
        return (List)(CollectionUtils.isEmpty(list) ? Lists.newArrayList() : (List)list.stream().map(function).collect(Collectors.toList()));
    }
    
    // 获取最里边的集合对象
    public static <E, R> List<R> flatMap(@NotNull List<E> list, Function<E, Collection<R>> function) {
        return (List)(CollectionUtils.isEmpty(list) ? Lists.newArrayList() : (List)list.stream().map(function).flatMap(Collection::stream).collect(Collectors.toList()));
    }
    
    // 过滤转对象
    public static <E, R> List<R> filterAndMap(List<E> list, Predicate<? super E> predicate, Function<E, R> function) {
        return (List)(CollectionUtils.isEmpty(list) ? Lists.newArrayList() : (List)list.stream().filter(predicate).map(function).collect(Collectors.toList()));
    }
    // 集合过滤
    public static <E> List<E> filer(List<E> list, Predicate<? super E> predicate) {
        return CollectionUtils.isEmpty(list) ? null : (List)list.stream().filter(predicate).collect(Collectors.toList());
    }

    // 获取一个对象
    public static <E> E filer(List<E> list, Predicate<? super E> predicate, E e) {
        return CollectionUtils.isEmpty(list) ? null : list.stream().filter(predicate).findFirst().orElse(e);
    }

    // 过滤获取一个对象
    public static <E> E filerAndFirst(List<E> list, Predicate<? super E> predicate) {
        return CollectionUtils.isEmpty(list) ? null : list.stream().filter(predicate).findFirst().orElse((Object)null);
    }
   //获取对象
    public static <E> E first(List<E> list) {
        return CollectionUtils.isEmpty(list) ? null : first(list, (Object)null);
    }

    public static <E> E first(List<E> list, E other) {
        return CollectionUtils.isEmpty(list) ? null : list.stream().findFirst().orElse(other);
    }

   // 去重
    public static <E> List<E> distinct(List<E> agentShopId) {
        return (List)agentShopId.stream().distinct().collect(Collectors.toList());
    }

    // 任意匹配
    public static <T> boolean anyMatch(List<T> collect, Predicate<T> predicate) {
        return collect.stream().anyMatch(predicate);
    }

   // 全部匹配
    public static <T> boolean allMatch(List<T> collect, Predicate<T> predicate) {
        return collect.stream().allMatch(predicate);
    }
}

学习stream抽象一下 链式编程