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