JDK1. 8 new features (I): stream

I What is stream?

1. General

The Java 8 API adds a new abstraction called stream, which allows you to process data in a declarative way.

This style regards the set of elements to be processed as a stream, which is transmitted in the pipeline and can be processed on the nodes of the pipeline, such as filtering, sorting, aggregation, etc.

The element flow is processed by intermediate operations in the pipeline, and finally the results of the previous processing are obtained by the final operation.

Briefly describe it as follows:

II for instance?

Now there is a string set. We need to filter out strings with length less than 2 in the set:

public static void main( String[] args ) {
    List<String> strings = Arrays.asList("ab","","bc","cd","abcd","jkl");
    List<String> stringList = new ArrayList<>();
    for (String str : strings){
        //如果长度大于2
        if (str.length() >= 2){
            //将字符串添加至新集合
            stringList.add(str);
        }
    }
    strings = stringList;
}

If stream is used as like as two peas:

public static void main( String[] args ) {
    List<String> strings = Arrays.asList("ab","jkl");
    //通过stream操作集合
    strings = strings.stream()
        //去掉长度小于2的字符串
        .filter(s -> s.length() >= 2)
        //转回集合
        .collect(Collectors.toList());
}

It can be seen that using stream API can easily write more efficient, concise and readable code

III How to use stream?

In short, there are two steps: generating flow and operating flow

1. Generate flow

To create a stream, you need to specify a data source, such as Java util. The subclass of collection, list or set, does not support map

1.1 stream () or parallelstream () method of collection interface

//将Set或List集合直接转换为stream对象
List<Person> personList = new ArrayList<>();
Set<Person> set = new HashSet<>();

Stream<Person> personStream1 = personList.stream();//生成串行流
Stream<Person> personStream2 = set.parallelStream();//生成并行流

1.2 Stream. of(),Arrays. stream,Stream. Empty() method

String[] strArr = {"a","a","a"};

//Stream.empty()
Stream<Integer> integerStream = Stream.empty();

//Stream.of() (方法内部调用的还是Arrays.stream)
Stream<String> stringStream = Stream.of(strArr);

//Arrays.stream
Stream<String> stringStream2 = Arrays.stream(strArr);

1.3 Stream. Concat() method

//已有的对象
Stream<Integer> integerStream = Stream.empty();
Stream<String> stringStream = Stream.of(strArr);
Stream<String> stringStream2 = Arrays.stream(strArr);

//合并两个流
Stream conStream1 = Stream.concat(stringStream,integerStream);
Stream conStream2 = Stream.concat(stringStream,stringStream2);

1.4 static files lines(path)

File file = new File("D://test.txt");
Stream<String> lines = Files.lines(file);

2. Operation flow

Stream operations can be divided into intermediate operations or final operations. The final operation returns a specific type of calculation result, while the intermediate operation returns the stream itself, which can follow other intermediate operations

//接下来的示例代码基于此集合
List<String> strings = Arrays.asList("ab","jkl");

2.1 filter (predicate): filter out elements with false result

//去掉长度小于2的字符串
strings = strings.stream()
    .filter(s -> s.length() >= 2)
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings
[ab,bc,cd,abcd,jkl]

2.2 map (fun): to convert the value of an element, you can refer to a method or directly use a lambda expression

strings = strings.stream()
    //为每个字符串加上“???”
    .map(s -> s += "???")
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings
[ab???,???,bc???,cd???,abcd???,jkl???]

2.3 limit (n): retain the first n elements

strings = strings.stream()
    //保留前3个
    .limit(3)
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings
[ab,bc]

2.4 skip (n): skip the first n elements

strings = strings.stream()
    //跳过前2个
    .skip(2)
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings
[bc,jkl]

2.5 distinct (): eliminate duplicate elements

strings = strings.stream()
    //过滤重复元素
    .distinct()
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings(过滤掉了一个空字符串)
[ab,jkl]

2.6 sorted(): sort elements through comparable

strings = strings.stream()
    //按字符串长度排序
    .sorted(
        //比较字符串长度
        Comparator.comparing(s -> s.length())
	)
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings(过滤掉了一个空字符串)
[,ab,jkl,abcd]

2.7 Peek (fun): the flow remains unchanged, but each element will be passed into fun for execution, which can be used for debugging

strings = strings.stream()
    //为字符串增加“???”
    .peek(s -> s += "???")
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings,和map对比,实际并没有改变集合
[ab,jkl]

2.8 flatmap (fun): if the element is a flow, flatten the flow to a normal element, and then convert the element

//将具有多重嵌套结构的集合扁平化

//获取一个两重集合
List<String> strings = Arrays.asList("ab","jkl");
List<String> strings2 = Arrays.asList("asd","bzxasdc","cddsdsd","adsdsg","jvcbl");
List<List<String>> lists = new ArrayList<>();
lists.add(strings);
lists.add(strings2);

//获取将两重集合压成一层
List<String> stringList = lists.stream()
    //将两重集合的子元素,即集合strings和strings2转成流再平摊
    .flatMap(Collection::stream)
    //返回集合
    .collect(Collectors.toList());

System.out.println(stringList);

//打印stringList
[ab,asd,bzxasdc,cddsdsd,adsdsg,jvcbl]

2.9 anymatch (fun), allmatch (fun): judge whether the elements in the flow match [final operation]

//allMatch
Boolean isAllMatch = strings.stream()
    //判断元素中是否有匹配“ab”的字符串,返回true或fals
    //判断元素中的字符串是否都与“ab”匹配,返回true或fals
    .allMatch(str -> str.equals("ab"));

System.out.println(isMatch);

//anyMatch
Boolean isAnyMatch = strings.stream()
    //判断元素中是否有匹配“ab”的字符串,返回true或fals
    .anyMatch(str -> str.equals("ab"));

System.out.println("isAnyMatch:" + isAnyMatch);
System.out.println("isAllMatch:" + isAllMatch);

//打印结果
isAnyMatch:true
isAllMatch:false

2.10 for each (fun): each data in iterative flow [final operation]

strings.stream()
    //遍历每一个元素
    .forEach(s -> System.out.print(s + "; "));

2.11 collect(): return result set [final operation]

strings = strings.stream()
    //返回集合
    .collect(Collectors.toList());

IV Use the intsummarystatistics class to process data

1. Intsummarystatistics class

The intsummarystatistics class, used in conjunction with stream in java8, is a status object used to collect statistics (such as count, minimum, maximum, sum and * average).

This class looks like this:

public class IntSummaryStatistics implements IntConsumer {
    private long count;
    private long sum;
    private int min = Integer.MAX_VALUE;
    private int max = Integer.MIN_VALUE;
    
    public IntSummaryStatistics() { }

    @Override
    public void accept(int value) {
        ++count;
        sum += value;
        min = Math.min(min,value);
        max = Math.max(max,value);
    }

    public void combine(IntSummaryStatistics other) {
        count += other.count;
        sum += other.sum;
        min = Math.min(min,other.min);
        max = Math.max(max,other.max);
    }

    public final long getCount() {
        return count;
    }


    public final long getSum() {
        return sum;
    }

    public final int getMin() {
        return min;
    }

    public final int getMax() {
        return max;
    }

    public final double getAverage() {
        return getCount() > 0 ? (double) getSum() / getCount() : 0.0d;
    }

    @Override
    public String toString() {
        return String.format(
            "%s{count=%d,sum=%d,min=%d,average=%f,max=%d}",this.getClass().getSimpleName(),getCount(),getSum(),getMin(),getAverage(),getMax());
    }
}

2. Use

This class is easy to understand. There are several internal methods:

2.1 get the total number of entries: getcount(),

2.2 get and: getsum(),

2.3 get the minimum value: getmin(),

2.4 get the maximum value: getmax(),

2.5 get average: getaverage()

Examples are as follows:

public static void main( String[] args ) {
    List<Integer> integerList = Arrays.asList(3,4,22,31,75,32,54);

    IntSummaryStatistics sta = integerList
        .stream()
        //将元素映射为对应的数据类型(int,double,long)
        .mapToInt(i -> i)
        //转换为summaryStatistics类
        .summaryStatistics();

    System.out.println("总共有 : "+ sta.getCount());
    System.out.println("列表中最大的数 : " + sta.getMax());
    System.out.println("列表中最小的数 : " + sta.getMin());
    System.out.println("所有数之和 : " + sta.getSum());
    System.out.println("平均数 : " + sta.getAverage());
}

//打印结果
总共有 : 7
列表中最大的数 : 75
列表中最小的数 : 3
所有数之和 : 221
平均数 : 31.571428571428573

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>