/**
* 創建Stream幾種方式
* 1.create from collection.
* 2.create from values.
* 3.create from arrays.
* 4.create from File.
* 5.create from Iterator.
* 6.create form Generate.
*//**
* create from collection.
*
* @return Stream
*/privatestatic Stream<String>createStreamFromCollection(){
List<String> list = Arrays.asList("hello","alex","alone","world","stream");return list.stream();}/**
* create form values
*
* @return Stream
*/privatestatic Stream<String>createStreamFromValues(){return Stream.of("hello","alex","alone","world","stream");}/**
* create form Arrays
*
* @return Stream
*/privatestatic Stream<String>createStreamFromArrays(){
String[] strings ={"hello","alex","alone","world","stream"};return Arrays.stream(strings);}/**
* create form File
*
* @return Stream
*/privatestatic Stream<String>createStreamFromFile(){
Path path = Paths.get("D:\\Test\\a.txt");try(Stream<String> streamFromFile = Files.lines(path)){
streamFromFile.forEach(System.out::println);return streamFromFile;}catch(IOException e){thrownewRuntimeException(e);}}/**
* create form Iterator
*
* @return Stream
*/privatestatic Stream<Integer>createStreamFromIterator(){
Stream<Integer> stream = Stream.iterate(0, n -> n +2).limit(10);return stream;}/**
* create form Generate
*
* @return Stream
*/privatestatic Stream<Double>createStreamFromGenerate(){return Stream.generate(Math::random).limit(10);}/**
* create form Generate
*
* @return Stream<Object>
*/privatestatic Stream<Obj>createObjStreamFromGenerate(){return Stream.generate(newObjSupplier()).limit(10);}staticclassObjSupplierimplementsSupplier<Obj>{privateint index =0;private Random random =newRandom(System.currentTimeMillis());@Overridepublic Obj get(){
index = random.nextInt(100);returnnewObj(index,"Name->"+ index);}}staticclassObj{privateint id;private String name;publicObj(int id, String name){this.id = id;this.name = name;}publicintgetId(){return id;}public String getName(){return name;}@Overridepublic String toString(){return"Obj{"+"name='"+ name +'\''+", id="+ id +'}';}}
Stream的常用方法
Stream Filter
/**
* Stream<T> filter(Predicate<? super T>........ predicate);
* 過濾
*/
List<Integer> list = Arrays.asList(1,2,3,4,5,6,6,7,7,1);
List<Integer> result = list.stream().filter(i -> i %2==0).collect(toList());
result .forEach(System.out::println);
Stream distinct
/**
* Stream<T> distinct();
* 去重
*/
result = list.stream().distinct().collect(toList());
result .forEach(System.out::println);
Stream skip
/**
* Stream<T> skip(long n);
* 跳過
*/
result = list.stream().skip(50).collect(toList());
result .forEach(System.out::println);
Stream limit
/**
* Stream<T> limit(long maxSize);
* 同sql中limit一致 , 限制
*/
result = list.stream().limit(50).collect(toList());
result .forEach(System.out::println);
Stream map
/**
* <R> Stream<R> map(Function<? super T, ? extends R> mapper);
* 轉map
*/
result = list.stream().map(i -> i *2).collect(toList());
result .forEach(System.out::println);