java8 常用操作再续

来源:互联网 发布:java poi 跨行 编辑:程序博客网 时间:2024/06/06 03:13


一,当我们使用stream的时候,需要包括如下的三个步骤.
简单说,对 Stream 的使用就是实现一个 filter-map-reduce 过程,产生一个最终结果,或者导致一个副作用(side effect)。


获取一个数据源(source)→ 数据转换→执行操作获取想要的结果


二,有多种方式生成 Stream Source


从 Collection 和数组
Collection.stream()
Collection.parallelStream()
Arrays.stream(T array) or Stream.of()
从 BufferedReader
java.io.BufferedReader.lines()
静态工厂
java.util.stream.IntStream.range()
java.nio.file.Files.walk()
自己构建
java.util.Spliterator
其它
Random.ints()
BitSet.stream()
Pattern.splitAsStream(java.lang.CharSequence)
JarFile.stream()


三,流的操作类型分为两种
Intermediate:namely,中间过渡操作,可以有多个.如下的都属于此种类型:


map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered


Terminal:namely,终端操作,只有一个.如下的都属于此种类型:


forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator


Short-circuiting:(短路)


{还有一种操作被称为 short-circuiting。用以指:
对于一个 intermediate 操作,如果它接受的是一个无限大(infinite/unbounded)的 Stream,但返回一个有限的新 Stream。
对于一个 terminal 操作,如果它接受的是一个无限大的 Stream,但能在有限的时间计算出结果。
当操作一个无限大的 Stream,而又希望在有限时间内完成操作,则在管道内拥有一个 short-circuiting 操作是必要非充分条件。}




anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit






四,流的构造与转换


1,构造流的几种常见方法


// 1. Individual values
Stream stream = Stream.of("a", "b", "c");
// 2. Arrays
String [] strArray = new String[] {"a", "b", "c"};
stream = Stream.of(strArray);
stream = Arrays.stream(strArray);
// 3. Collections
List<String> list = Arrays.asList(strArray);
stream = list.stream();


2,数值流的构造


IntStream.of(new int[]{1, 2, 3}).forEach(System.out::println);
IntStream.range(1, 3).forEach(System.out::println);
IntStream.rangeClosed(1, 3).forEach(System.out::println);


3,流转换为其它数据结构


// 1. Array
String[] strArray1 = stream.toArray(String[]::new);
// 2. Collection
List<String> list1 = stream.collect(Collectors.toList());
List<String> list2 = stream.collect(Collectors.toCollection(ArrayList::new));
Set set1 = stream.collect(Collectors.toSet());
Stack stack1 = stream.collect(Collectors.toCollection(Stack::new));
// 3. String
String str = stream.collect(Collectors.joining()).toString();



五,java.util.function 中




Function的使用


该接口有两个方法,如下所示:


// 1,Compute the result of applying the function to the input argument


R apply(T t)   


// 2,Combine with another function returning a function which performs both functions.


default <V> Function<T,V> compose(Function<? super R,? extends V> after)




    static void modifyTheValue(int valueToBeOperated,Function<Integer, Integer> function){
        int newValue = function.apply(valueToBeOperated);
        System.out.println(newValue);
    }


    public static void main(String[]args){


        int valueToBeOper=20;
        int incr=2;
        new Demo3().modifyTheValue(valueToBeOper,p->p+incr);
    }


    //运行结果是 22




Supplier 接口的使用.


里面只有这么一个方法:
T get();


举栗子:


    public void method2(){
        Random seed=new Random();
        Supplier<Integer> ran= seed::nextInt;
        Stream.generate(ran).limit(10).forEach(System.out::println);
    }




运行结果:
-730632575
-1501251296
-296435633
1018244280
-1996563966
-864662929
-501794018
1316711404
-346781493
-907325722




六,用 Collectors 来进行 reduction 操作


java.util.stream.Collectors 类的主要作用就是辅助进行各类有用的 reduction 操作,例如转变输出为 Collection,把 Stream 元素进行归组。


groupingBy/partitioningBy  //分组,分成几个部分


如下是举栗子


    public void method7(){
        Map<Integer,List<People>> peopleGroups=Stream.generate(new PersonSupplier()).limit(100).collect(Collectors.groupingBy(People::getAge));
        Iterator iterator=peopleGroups.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Integer,List<People>>  integerListEntry=(Map.Entry)iterator.next();
            System.out.println("Age:"+integerListEntry.getKey()+"="+integerListEntry.getValue().size());
        }
    }


运行结果如下:


Age:67=1
Age:51=1
Age:84=1
Age:54=1
Age:38=1
Age:73=1
Age:91=1
Age:77=1
Age:30=1
Age:78=1




    public void method8(){
        Map<Boolean,List<People>> children=Stream.generate(new PersonSupplier()).limit(100).collect(Collectors.partitioningBy(p->p.getAge()<18));
        System.out.println("Children` number is :"+children.get(true).size());
        System.out.println("Adult`s number is :"+children.get(false).size());
    }


运行结果如下:


Children` number is :21
Adult`s number is :79



七,java.util.stream 中的Stream接口的说明.


A sequence of elements supporting sequential and parallel aggregate operations. 


namely,该接口的功能是:对元素支持序列和并发的聚合操作


如下是我们常用到的一些方法:


1,boolean allMatch(Predicate<? super T> predicate)  //Returns whether all elements of this stream match the provided predicate.


2,boolean anyMatch(Predicate<? super T> predicate)  //Returns whether any elements of this stream match the provided predicate.


3,static <T> Stream.Builder<T> builder()            //Returns a builder for a Stream.


4,<R,A> R collect(Collector<? super T,A,R> collector)  //Performs a mutable reduction operation on the elements of this stream using a Collector.


5,static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)


//Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.


6,long count()  //Returns the count of elements in this stream.


7,Stream<T> distinct()  //Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.


8,static <T> Stream<T> empty() //Returns an empty sequential Stream.


9,Stream<T> filter(Predicate<? super T> predicate) //Returns a stream consisting of the elements of this stream that match the given predicate.


10,Optional<T> findAny() //Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty.


11,Optional<T> findFirst() //Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.


12,<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
//Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.


13,DoubleStream flatMapToDouble(Function<? super T,? extends DoubleStream> mapper)
//Returns an DoubleStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.


14,IntStream flatMapToInt(Function<? super T,? extends IntStream> mapper)
//Returns an IntStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.


15,LongStream flatMapToLong(Function<? super T,? extends LongStream> mapper)
//Returns an LongStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
16,void forEach(Consumer<? super T> action) //Performs an action for each element of this stream.


17,void forEachOrdered(Consumer<? super T> action)
Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.


18,static <T> Stream<T> generate(Supplier<T> s)
Returns an infinite sequential unordered stream where each element is generated by the provided Supplier.


19,static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)
//Returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc.


20,Stream<T> limit(long maxSize)  //Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.


21,<R> Stream<R> map(Function<? super T,? extends R> mapper)  //Returns a stream consisting of the results of applying the given function to the elements of this stream.




22,DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper) //Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.


23,IntStream mapToInt(ToIntFunction<? super T> mapper) //Returns an IntStream consisting of the results of applying the given function to the elements of this stream.


24,LongStream mapToLong(ToLongFunction<? super T> mapper) //Returns a LongStream consisting of the results of applying the given function to the elements of this stream.


25,Optional<T> max(Comparator<? super T> comparator) //Returns the maximum element of this stream according to the provided Comparator.


26,Optional<T> min(Comparator<? super T> comparator) //Returns the minimum element of this stream according to the provided Comparator.


27,boolean noneMatch(Predicate<? super T> predicate)  Returns whether no elements of this stream match the provided predicate.


28,static <T> Stream<T> of(T... values) //Returns a sequential ordered stream whose elements are the specified values.


29,static <T> Stream<T> of(T t) //Returns a sequential Stream containing a single element.


30,Stream<T> peek(Consumer<? super T> action)
//Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.


31,Stream<T> skip(long n) //Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream.


32,Stream<T> sorted()  //Returns a stream consisting of the elements of this stream, sorted according to natural order.


33,Stream<T> sorted(Comparator<? super T> comparator) //Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.


34,Object[] toArray() //Returns an array containing the elements of this stream.




八,java.util.stream 中的Collectors 类.


常用的方法:


1,toSet()  //Returns a Collector that accumulates the input elements into a new Set.




2,toList()  //Returns a Collector that accumulates the input elements into a new List.


3,toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)
//Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.


4,toCollection(Supplier<C> collectionFactory)
//Returns a Collector that accumulates the input elements into a new Collection, in encounter order.


5,partitioningBy(Predicate<? super T> predicate)
//Returns a Collector which partitions the input elements according to a Predicate, and organizes them into a Map<Boolean, List<T>>.


6,maxBy(Comparator<? super T> comparator)  //Returns a Collector that produces the maximal element according to a given Comparator, described as an Optional<T>.


7,static <T> Collector<T,?,Optional<T>> minBy(Comparator<? super T> comparator)
//Returns a Collector that produces the minimal element according to a given Comparator, described as an Optional<T>.


8,joining()  //Returns a Collector that concatenates the input elements into a String, in encounter order.


9,groupingBy(Function<? super T,? extends K> classifier)
//Returns a Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function, and returning the results in a Map.


10,counting()
Returns a Collector accepting elements of type T that counts the number of input elements.



九,java.util.function包中的 Predicate 类.


Static utility methods pertaining to Predicate instances. namely,一些与或非异或等的操作集合.


常用的方法如下:


1,static <T> Predicate<T> and(Iterable<? extends Predicate<? super T>> predicates)


//Returns a predicate that evaluates to true if all of the component predicates evaluate to true.


2,static <T> Predicate<T> and(Predicate<? super T>... predicates)


//Returns a predicate that evaluates to true if all of the component predicates evaluate to true.


3,static <T> Predicate<T> isEqual(Object target)


//Returns a predicate who's result matches Objects.equals(target, t).


4,static <T> Predicate<T> isSame(Object target)


//Returns a predicate that who's result is target == object.


5,static <T> Predicate<T> or(Iterable<? extends Predicate<? super T>> predicates)


//Returns a predicate that evaluates to true if any of the component predicates evaluate to true.


6,static <T> Predicate<T> or(Predicate<? super T>... predicates)


//Returns a predicate that evaluates to true if any of the component predicates evaluate to true.


7,static <T> Predicate<T> xor(Iterable<? extends Predicate<? super T>> predicates)


//Returns a predicate that evaluates to false if all or none of the component predicates evaluate to true.


8,static <T> Predicate<T> xor(Predicate<? super T>... predicates)


//Returns a predicate that evaluates to false if all or none of the component predicates evaluate to true.


十,在java.util.function包中的接口 Consumer中,


An operation which accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.


namely,接受单个参数,不会返回结果.




1,void accept(T t) //Accept an input value.


2,default Consumer<T> chain(Consumer<? super T> other)  //Returns a Consumer which performs in sequence the apply methods of multiple Consumers.














附:


flatMap的一个很好的例子:
List<String> output = reader.lines().
 flatMap(line -> Stream.of(line.split(REGEXP))).
 filter(word -> word.length() > 0).
 collect(Collectors.toList());