关于Java Stream 的例子(书名:Java9编程参考官方大全第29章的第一个例子)

本文通过实例演示了如何使用 Java 的 Stream API 来处理集合数据,包括获取最大最小值、排序、过滤等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.*;
import java.util.stream.*;

public class StreamDemo {
    public static void main(String[] args){
        ArrayList<Integer> myList=new ArrayList<>();
        myList.add(7);
        myList.add(18);
        myList.add(10);
        myList.add(24);
        myList.add(17);
        myList.add(5);
        System.out.println("Original list:"+myList);
        //Obtain a Stream to the array list.
        Stream<Integer> myStream=myList.stream();
        //obtain the max and min value by use of min(),max(),isPresent(),and get().
        Optional<Integer> minVal=myStream.min(Integer::compare);
        if(minVal.isPresent()) System.out.println("Minimum value: "+minVal.get());
        //must obtain a new stream because min() is a terminal operation that consumed the stream.
        //Stream<Integer> 
        //myStream=myList.stream();
        Stream<Integer>     myStream2=myList.stream();
        //obtain the max and min value by use of min(),max(),isPresent(),and get().
        Optional<Integer> maxVal=myStream2.max(Integer::compare);
        if(maxVal.isPresent()) System.out.println("Maximum value: "+maxVal.get());
        //sort the stream by use of sorted().
        Stream<Integer> sortedStream=myList.stream().sorted();
        //Display the sorted stream by use foreach().
        System.out.println("Sorted stream: ");
        sortedStream.forEach((n)->System.out.print(n+" "));
        System.out.println();
        //Display only the odd value by use of filter().
        Stream<Integer> oddVals=myList.stream().sorted().filter((n)->(n%2)==1);
        System.out.println("Odd values: ");
        oddVals.forEach((n)->System.out.print(n+" "));
        System.out.println();
        //Display only the odd values that are greater than 5,Notice that two filter operations are pipelined.
        oddVals=myList.stream().filter((n)->(n%2)==1).filter((n)->n>5);
        System.out.println("Odd values greater than 5 : ");
        oddVals.forEach((n)->System.out.print(n+" "));
        System.out.println();
        
    }

}
执行结果:

Original list:[7, 18, 10, 24, 17, 5]
Minimum value: 5
Maximum value: 24
Sorted stream: 
5 7 10 17 18 24 
Odd values: 
5 7 17 
Odd values greater than 5 : 
7 17 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值