Use Java Stream

of () array and receiving a stream created, then map () to obtain the square of each element, DISTINCT () to weight, then use collect () the flow element becomes List

@Test
public void mapTest(){
    List<Integer> squaresList = Stream.of(3, 2, 2, 3, 7, 3, 5)
            .map(e -> e*e)
            .distinct()
            .collect(Collectors.toList());
}

Collection use stream () Gets the stream, filter () is filtered off the empty string, count () Count

@Test
public void filerTest(){
    List<String> stringList = Arrays.asList("abc", "d", "ef", "ghi", "","123", "bcd","");
    long count = stringList.stream().filter(string -> string.isEmpty()).count();
    // 2
}

filter () filter out non-empty strings, Skip () to filter out the first three, and generated using commas to separate String

@Test
public void collectTest(){
    List<String> stringList = Arrays.asList("abc", "d", "ef", "ghi", "","123", "bcd","");
    String mergedString = stringList.stream().filter(string -> !string.isEmpty()).skip(3).collect(Collectors.joining(", "));
    // ghi, 123, bcd
}

Some statistics produced collectors is also very useful.
They are mainly used for the basic type int, double, long and the like, which may be used to generate statistics similar to the following.

@Test
public void statTest(){
    List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

    IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();

    System.out.println("列表中最大的数 : " + stats.getMax());//7
    System.out.println("列表中最小的数 : " + stats.getMin());//2
    System.out.println("所有数之和 : " + stats.getSum());//25
    System.out.println("平均数 : " + stats.getAverage());//3.5714285714285716
}

Parallel execution order may be different from the original order.
filter () filter out non-empty strings, limit () before the two filter

@Test
public void parallelStreamTest(){
    List<String> stringList = Arrays.asList("abc", "d", "ef", "ghi", "","123", "bcd","");
    stringList = stringList.parallelStream().filter(string -> !string.isEmpty()).limit(2).collect(Collectors.toList());
    // [abc, d]
}

The combined flow of the two is not closed, if there is a flow of first use count (), collect () or forEach (), it will close the stream, you will get an error when merging
stream has already been operated upon or closed

@Test
public void concatTest(){
    Stream<Integer> stream1 = Stream.of(1,2,3);
    Stream<Integer> stream2 = Stream.of(4,5,6);

    // 4,5,6,
    Stream.concat(stream1, stream2).filter(e -> e > 3).forEach(e -> System.out.print(e + ","));
}

Reference:
the Java 8 Stream
the Java Stream flow of
understanding Java8 in parallelStream

Published 69 original articles · won praise 13 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_36160730/article/details/104390111