New Features of Java 8 (2) Streaming Programming of Stream Collection

Stream-collection stream

Introduction

Stream is an enhancement to collection operations. Stream is not an element of a collection, is not a data structure, and is not responsible for data storage. The stream is more like an iterator, it can traverse each element in the collection in one direction, and it is not loopable.

Why use a collection of streaming programming

Sometimes, when operating on elements in the collection, you need to use the results of other operations. In this process, the collective flow programming will greatly simplify the amount of programming code. Read the data in the data source into a stream, you can operate on the data in this stream (delete, filter...), the result of each processing is a stream object, you can continue to operate on this stream.

Steps of streaming programming

  1. Get data source: read the data of the collection into a stream;
  2. Intermediate operation: processing the stream, the result is still a stream object;
  3. Termination operation: Integrate the data in the stream and close the stream object.

: During intermediate operation and termination operation, the basic methods are all functional interfaces, and lamda expressions are needed to simplify the code.

1. Acquisition of data source

Read the data into a stream, the operations on the stream will not affect the data of the data source, only the remaining data in the stream is filtered

//集合
public static Stream<Integer> getDatasource(){
    
    
    List<Integer> list = new ArrayList<>();      
    Collections.addAll(list,1,2,3,4,5,6,7,8,9);        
    return list.stream();//同步流       
    //return list.parallelStream();//异步流
}

//包装类数组
public static Stream<Integer> getAraayDatasource(){
    
    
    Integer[] array = new Integer[]{
    
    1,2,3,4,5,6,7,8,9};
    Stream<Integer> stream = Arrays.stream(array);
    return stream;
}

//基本数据数组
public static IntStream getIntDatasource(){
    
    
    int[] array = new int[]{
    
    1,2,3,4,5,6,7,8,9};
    IntStream intStream = Arrays.stream(array);
    return intStream;
}

2. Terminate operation

Extract the desired data in the stream through the final operation, and then destroy the stream. An exception will be thrown when the operation is closed.

  • collect: Collect the data in the stream and process the data.
public static void main(String[] args) {
    
    
    Stream<Integer> stream = Datasource.getDatasource();

    //[1, 2, 3, 4, 5, 6, 7, 8, 9]
    //Set<Integer> set = stream.collect(Collectors.toSet());
    
    //{2=3, 3=4, 4=5, 5=6, 6=7, 7=8, 8=9, 9=10, 10=11}
    //Map<Integer, Integer> map = stream.collect(Collectors.toMap(i -> i + 1, i -> i + 2));
    
    //[1, 2, 3, 4, 5, 6, 7, 8, 9]
    List<Integer> list = stream.collect(Collectors.toList());

    System.out.println(list);
}
  • Reduce: gather the data in the stream according to certain rules. A functional interface that returns two parameters in a method
public static void main(String[] args) {
    
    
    Stream<Integer> stream = Datasource.getDatasource();
    Optional<Integer> integerOptional = stream.reduce((p1, p2) -> p1 + p2);
    Integer integer = integerOptional.get();
    System.out.println(integer);//45

}
  • count: count the number of data in the stream
public static void main(String[] args) {
    
    
    Stream<Integer> stream = Datasource.getDatasource();
    System.out.println(stream.count());
}
  • foreach: Traverse the data in the stream. A functional interface with no return value for a parameter in a method
public static void main(String[] args) {
    
    
    Stream<Integer> stream = Datasource.getDatasource();
    stream.forEach(System.out::println);
}
  • max&min: Find the maximum and minimum values ​​according to the specified rules
public static void main(String[] args) {
    
    
    Stream<Integer> stream = Datasource.getDatasource();
    Integer max = stream.max(Integer::compareTo).get();
    Integer min = stream.min(Integer::compareTo).get();
}
  • Matching:

    allmatch: all elements in the stream match the rules, return true

    anymstch: Any element in the stream satisfies the rule and returns true

    nonematch: none of the elements in the stream satisfy the rule, return true

public static void main(String[] args) {
    
    
    Stream<Integer> stream = Datasource.getDatasource();
    //System.out.println(stream.allMatch(integer -> integer > 5));//false
    //System.out.println(stream.anyMatch(integer -> integer > 5));//true
    System.out.println(stream.noneMatch(integer -> integer <0));//true
}
  • find

    findfirst: returns the first element in the stream;

    firstany: return any of the streams (usually the first one); not necessarily when multithreaded

public static void main(String[] args) {
    
    
    Stream<Integer> stream = Datasource.getDatasource();//并行流
    //System.out.println(stream.findFirst().get());//1
    System.out.println(stream.findAny().get());//6
}
---
public static void main(String[] args) {
    
    
    Stream<Integer> stream = Datasource.getDatasource();//串行流
    //System.out.println(stream.findFirst().get());//1
    System.out.println(stream.findAny().get());//1
}
  • IntStream another termination operation
public static void main(String[] args) {
    
    
    IntStream intStream = Datasource.getIntDatasource();
    
    int asInt = intStream.max().getAsInt();//最大值
    int asInt1 = intStream.min().getAsInt();//最小值
    int sum = intStream.sum();//和
    long count = intStream.count();//元素个数
    double v = intStream.average().getAsDouble();//平均值
    
    IntSummaryStatistics summaryStatistics = intStream.summaryStatistics();//数据分析合集
    
    double average = summaryStatistics.getAverage();
    long count1 = summaryStatistics.getCount();
    int max = summaryStatistics.getMax();
    int min = summaryStatistics.getMin();
}

3. Intermediate operation

Convection processing can be performed multiple times

  • filter: Condition filtering, remove elements that do not meet the condition
stream.filter(integer -> integer>5).forEach(System.out::println);
  • distinct: Remove duplicate elements in the stream. The principle of deduplication is the same as HashSet, entity classes need to rewrite hashcode() and equls
stream.distinct().forEach(System.out::println);
  • sorted:

    1. [No parameters] Sorting entity class needs to implement Comparable interface;

    2. [With parameters] Custom interface implementation

stream.sorted().forEach(System.out::println);
  • limit & skip:

    limit: limit, intercept a certain amount of data

    skip: skip, drop the specified amount of data

stream.distinct()
    .limit(5)
    .skip(2)
    .sorted()
    .forEach(System.out::println);
  • map & flatmap

    map: Provide rules to replace data in the stream with new data

    flatmap: flat map, read the data in the container in the stream directly into the stream

 stream.map(integer -> "第"+integer+"个数据").forEach(System.out::println);
//第1个数据、第2个数据、第3个数据、第4个数据、第5个数据、第6个数据、第7个数据、第8个数据、第9个数据
public static void main(String[] args) {
    
    
    String[] array = new String[]{
    
    "hello","world"};
    Stream<String> stream = Arrays.stream(array);
    //统计出现的字符
    // stream.map(String::toCharArray)
    	.forEach(e-> System.out.println(e));//{'h','e','l','l','o'} ,{'w','o','r','l','d'}
    stream.map(s->s.split(""))//{"h","e","l","l","o"} ,{"w","o","r","l","d"}
        .flatMap(Arrays::stream)//{"h","e","l","l","o","w","o","r","l","d"}
        .distinct()//{"h","e","l","o","w","r","d"}
        .forEach(System.out::print);//helowrd
}
  • mapToInt: a parameter, the return value of type int, the return stream object is IntStream
IntStream intStream = stream.mapToInt(Integer::byteValue);
IntSummaryStatistics summaryStatistics = intStream.summaryStatistics();

4. Other operations of Collectors tools

  1. maxby(), minby(), summingInt(), averagingInt(), summarizingInt(): can be replaced by mapToInt()
  2. joining: Join the data in the stream into a string, only operate Stream
public static void main(String[] args) {
    
    
    String[] array = new String[]{
    
    "hello","world","java","c++"};

    Stream<String> stream = Arrays.stream(array);
    //参数一:分隔符
    //参数二:前缀
    //参数三:后缀
    String collect = stream.collect(Collectors.joining("-", "[", "]"));

    System.out.println(collect);//[hello-world-java-c++]
}

Guess you like

Origin blog.csdn.net/qq_38473355/article/details/108720955