美文网首页
java8 lambda stream常用用法

java8 lambda stream常用用法

作者: jhon_11 | 来源:发表于2021-02-24 23:27 被阅读0次

stream api

public interface Stream<T> extends BaseStream<T, Stream<T>> {
 
    Stream<T> filter(Predicate<? super T> predicate);
 
    <R> Stream<R> map(Function<? super T, ? extends R> mapper);
 
    IntStream mapToInt(ToIntFunction<? super T> mapper);
 
    LongStream mapToLong(ToLongFunction<? super T> mapper);
 
    DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper);
 
    <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
 
    IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper);
 
    LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper);
 
    DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper);
 
    Stream<T> distinct();
 
    Stream<T> sorted();
 
    Stream<T> sorted(Comparator<? super T> comparator);
 
    Stream<T> peek(Consumer<? super T> action);
 
    Stream<T> limit(long maxSize);
 
    Stream<T> skip(long n);
 
    void forEach(Consumer<? super T> action);
 
    void forEachOrdered(Consumer<? super T> action);
 
    Object[] toArray();
 
    <A> A[] toArray(IntFunction<A[]> generator);
 
    T reduce(T identity, BinaryOperator<T> accumulator);
 
    Optional<T> reduce(BinaryOperator<T> accumulator);
 
    <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);
 
    <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner);
 
    <R, A> R collect(Collector<? super T, A, R> collector);
 
    Optional<T> min(Comparator<? super T> comparator);
 
    Optional<T> max(Comparator<? super T> comparator);
 
    long count();
 
    boolean anyMatch(Predicate<? super T> predicate);
 
    boolean allMatch(Predicate<? super T> predicate);
 
    boolean noneMatch(Predicate<? super T> predicate);
 
    Optional<T> findFirst();
 
    Optional<T> findAny();
 
    public static <T> Builder<T> builder() {
        return new Streams.StreamBuilderImpl<>();
    }
 
    public static <T> Stream<T> empty() {
        return StreamSupport.stream(Spliterators.<T> emptySpliterator(), false);
    }
 
    public static <T> Stream<T> of(T t) {
        return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
    }
 
    @SafeVarargs
    @SuppressWarnings("varargs") // Creating a stream from an array is safe
    public static <T> Stream<T> of(T... values) {
        return Arrays.stream(values);
    }
 
    public static <T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) {
        Objects.requireNonNull(f);
        final Iterator<T> iterator = new Iterator<T>() {
            @SuppressWarnings("unchecked")
            T t = (T) Streams.NONE;
 
            @Override
            public boolean hasNext() {
                return true;
            }
 
            @Override
            public T next() {
                return t = (t == Streams.NONE) ? seed : f.apply(t);
            }
        };
        return StreamSupport.stream(
                Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED | Spliterator.IMMUTABLE), false);
    }
 
    public static <T> Stream<T> generate(Supplier<T> s) {
        Objects.requireNonNull(s);
        return StreamSupport.stream(new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s),
                false);
    }
 
    public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) {
        Objects.requireNonNull(a);
        Objects.requireNonNull(b);
 
        @SuppressWarnings("unchecked")
        Spliterator<T> split = new Streams.ConcatSpliterator.OfRef<>((Spliterator<T>) a.spliterator(),
                (Spliterator<T>) b.spliterator());
        Stream<T> stream = StreamSupport.stream(split, a.isParallel() || b.isParallel());
        return stream.onClose(Streams.composedClose(a, b));
    }
 
    public interface Builder<T> extends Consumer<T> {
        @Override
        void accept(T t);
 
        default Builder<T> add(T t) {
            accept(t);
            return this;
        }
 
        Stream<T> build();
 
    }
}

将list转成map映射

简介

有一个list,需要将里面的对象转成map映射,用lambda写法比较方便简洁,怎么实现呢?
例子:

@Data
public class UserDto{
   private String userName;
   private Integer age;
   private String desc;
}

List<UserDto> list = new ArrayList<>();

我想将list中的元素转换成以userName为key的map映射,该如何实现

解决方案

使用lambda实现

list.stream().map(UserDto::getUserName, t->t).collect(Collectiors.toMap());

使用lambda将list聚合成map——groupby使用

简介

有一个list,需要将age相同的聚合成不同的list,怎么实现呢?
例子:

@Data
public class UserDto{
   private String userName;
   private Integer age;
   private String desc;
}

List<UserDto> list = new ArrayList<>();

解决方案

Map<String, List<UserDto>> map = list.parallelStream()
                .collect(Collectors.groupingBy(UserDto::getAge));

将一个list对象中的多个元素迁移到另外一个list

简介

有一个list对象,我想将该list中对象的某几个元素放入到另外一个对象中并聚合成另外一个list对象

例子:

@Data
public class UserDto{
   private String userName;
   private Integer age;
   private String desc;
}

@Data
public class SimpleUserDto{
   private String userName;
   private Integer age;
}

将userDto中的userName,age属性转到simpleUserDto并聚合为一个list对象

解决方案

List<SimpleUserDto> simpleUserDtos = list.stream().map(user -> {
  SimpleUserDto dto = new SimpleUserDto();
  dto.setUserName(user.getUserName());
  dto.setAge(user.getAge());
  return dto;
}).collect(Collectors.toList());

java8 stream接口终端操作 count,anyMatch,allMatch,noneMatch

简介

count方法,跟List接口的size一样,返回的都是这个集合流的元素的长度,不同的是,流是集合的一个高级工厂,中间操作是工厂里的每一道工序,我们对这个流操作完成后,可以进行元素的数量的和;
anyMatch表示,判断的条件里,任意一个元素成功,返回true
allMatch表示,判断条件里的元素,所有的都是,返回true
noneMatch跟allMatch相反,判断条件里的元素,所有的都不是,返回true
例子:

List<String> strs = Arrays.asList("a", "a", "a", "a", "b");
        boolean aa = strs.stream().anyMatch(str -> str.equals("a"));
        boolean bb = strs.stream().allMatch(str -> str.equals("a"));
        boolean cc = strs.stream().noneMatch(str -> str.equals("a"));
        long count = strs.stream().filter(str -> str.equals("a")).count();
        System.out.println(aa);// TRUE
        System.out.println(bb);// FALSE
        System.out.println(cc);// FALSE
        System.out.println(count);// 4

相关文章

网友评论

      本文标题:java8 lambda stream常用用法

      本文链接:https://www.haomeiwen.com/subject/ppvefltx.html