Various usages of Java8--Stream (1)

In the operation of collections in java8, Stream has been added, and with lmbda expression, it has greatly improved our processing efficiency of collection data. Stream is the key abstraction concept in Java 8 for processing collections, and can perform complex operations such as searching, screening, filtering, sorting, aggregation, and data mapping.

Operation classification

  • Intermediate operations:
    • Stateless: The processing of elements is not affected by previous elements, such as: map(), mapToInt(), flatMap(), flatMapToLong(), peek(), unordered(), filter()
    • Stateful: The operation can only continue after all elements are obtained, such as: distinct(), sorted(), limit(), skip()
  • End operation:
    • Non-short-circuit operation: all elements must be processed to get the result, such as: foreach(), forEachOrdered(), toArray(), reduce(), collect(), max(), min(), count()
    • Short-circuit operation: the result can be obtained when certain elements meet the conditions, ru: anyMatch(), allMatch(), noneMatch(), findFirst(), findAny()

Stream creation

1. Create through collection array:

  1. Collection.stream(): The most commonly used list.stream() at that time
    // 顺序流
    Stream<Object> stream = new ArrayList<>().stream();
    
    // 并行流
    Stream<Object> parallelStream = new ArrayList<>(). parallelStream();
  2. Array.stream: 
     IntStream stream = Arrays.stream(new int[10]);
  3. Static methods of Stream: of(), iterate(), generate(), builder().build();

    Stream<Integer> of = Stream.of(1,2,3);
    
    //生成无限的顺序流, 需要用limit限制元素个数
    Stream<Integer> iterate = Stream.iterate(0, x -> x + 1).limit(2);
    
    //生成无限的无序流, 需要limit限制元素个数
    Stream<Double> generate = Stream.generate(Math::random).limit(2);
    
    Stream<Object> build = Stream.builder().add("123).build();

    Here is a brief explanation of the simple distinction between stream and parallelStream: stream is a sequential stream; parallelStream is a parallel stream, and internally operates on the stream in a multi-threaded parallel execution mode, so there is no order requirement for data processing in the stream.

Introduction and use of Stream API: 

1、foreach、forEachOrdered

forEachOrdered is suitable for iteration in the case of parallel flow, which can ensure the order of iteration

Stream.of("a,b,c","d,e,f")
        .forEach(System.out::println);

2、find:findFirst、findAny

findFirst, findAny Find the first, find any return type is Optional

Optional<String> any = Stream.of("a,b,c", "d,e,f").findAny();

String first = Stream.of("a,b,c", "d,e,f").findFirst().get();

3、match: noneMatch、allMatch、anyMatch

Whether there is a qualified element in the data stream returns a bool value

  • noneMatch: no element in the data stream meets the condition, return true
  • allMatch: All elements in the data stream meet the conditions, return true
  • anyMatch: If any element in the data stream meets the condition, return true
Stream.of("a,b,c","d,e,f").noneMatch(s -> s.equals("123"));
Stream.of("a,b,c","d,e,f").allMatch(s -> s.equals("123"));
Stream.of("a,b,c","d,e,f").anyMatch(s -> s.equals("123"));

4. Aggregation: max, min, count

min, max are the most value operations, which require a custom comparator to return the largest and smallest values ​​in the data stream

count counts the number of elements

Optional<Integer> max = Stream.of(1, 2, 3, 4).max((i1, i2) -> i1.compareTo(i2));

long num = Stream.of(1, 2, 3, 4).count();

5、reduce

The reduction operation reduces the value of the entire data stream to one value. The bottom layer of count, min and max is to use reduce

  • 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);

reduce has three overridden methods, the first one we often use, which directly returns the object we want.

Integer reduce = Stream.of(1, 2, 3, 4).reduce(0, (i1, i2) -> i1 + i2);

6. Map conversion, object A -> B

mapToInt, mapToLong, and mapToDouble provide operators for converting to int, long, and double by default.

List<String> list = Stream.of(1, 2, 3, 4).map(i -> String.valueOf(i)).collect(Collectors.toList());

Generally, in practical applications, we will extract a certain field value of T in List<T> to form a list / set: 

List<String> nameList = list.stream()
                            .map(User::getName)
                            .collect(Collectors.toList())

7. FaltMap data flattening

flatmapToInt, flatmapToLong, and flatmapToDouble provide operators for flattening into int, long, and double by default

Stream.of("a,b,c", "d,e,f")
        .flatMap(s -> Stream.of(s.split(",")))
        .forEach(System.out::println);

8. Screening: filter, limit, skip

  • filter: filter
  • limit( long n): limit the number of returned data
  • skip( long n): adjust the first few pieces of data, and get the following data
Stream.of(1, 2, 3, 4, 5)
        .filter(i -> i < 5)
        .skip(1)
        .limit(2);

9. distinct deduplication 

Stream.of(1, 2, 2, 4, 2).distinct();

10. peek out

Consume data in advance

Stream.of(1, 2, 3, 4, 5).peek(i -> i++); 

11. sorted

To sort elements, the premise is to implement the Comparable interface, or you can customize the comparator

Stream.of(2,5,3,1,0).sorted()

12、collect 

The collection operation is to collect all the data. This operation is very important. The official Collectors provide a lot of collectors. It can be said that the core of Stream lies in Collectors. In this regard, we will write a special article to introduce the use of Collectors

Stream.of(1,2,3,1,2)
        .collect(Collectors.toSet())
        .forEach(System.out::println);

Guess you like

Origin blog.csdn.net/zhoushimiao1990/article/details/127286689