Java 提效神器 Stream 的冷門技巧

Stream

使用這個方法建立一個 Stream 對象。java

new ArrayList<>().stream()
複製代碼

Filter

過濾器,裏面傳遞一個函數,這個函數的返回結果若是爲 true 則保留這個元素,不然的話丟棄這個元素。編程

stringCollection
                .stream()
                .filter((s) -> s.startsWith("a"))
                .forEach(System.out::println);
複製代碼

Foreach

遍歷,消費。數組

stringCollection
                .stream()
                .filter((s) -> s.startsWith("a"))
                .forEach(System.out::println);
複製代碼

Map

這個功能也是遍歷,可是他是有返回值的,而上面的 Foreach 是沒有返回值的,僅僅是單純的消費。並且 Foreach 不可以鏈式調用,由於沒有返回值,可是 Map 沒問題。安全

stringCollection
                .stream()
                .map(String::toUpperCase)
                .sorted(Comparator.reverseOrder())
                .forEach(System.out::println);
複製代碼

Sorted

這個方法是用來排序的,裏面傳遞的函數就是一個比較器,也能夠不傳遞參數,使用默認的就好。markdown

stringCollection
                .stream()
                .sorted(( x, y)-> y.length()-x.length())
                .filter((s) -> s.startsWith("a"))
                .forEach(System.out::println);
複製代碼

Match

根據在給定的 stream 對象中是否含有指定內容返回 true 或者 false 。多線程

具體的有:併發

  • allMatch
  • anyMatch
  • noneMatch
boolean anyStartsWithA = stringCollection
                .stream()
                .anyMatch((s) -> s.startsWith("a"));

        boolean allStartsWithA = stringCollection
                .stream()
                .allMatch((s) -> s.startsWith("a"));

        boolean noneStartsWithZ = stringCollection
                .stream()
                .noneMatch((s) -> s.startsWith("z"));
複製代碼

count

計算集合中的元素的個數。app

long startsWithB = stringCollection
        .stream()
        .filter((s) -> s.startsWith("b"))
        .count();
複製代碼

reduce

這個函數就是相似於斐波那契數列,每次傳遞的參數是上一次的結果和從集合中取出的新元素。第一次默認取出了第一個元素和第二個元素。dom

簡單的例子就是,第一次取出 0,1 第二次取出 第一次reduce的結果做爲第一個參數,取出 2 做爲第二個參數,以此類推。編程語言

Optional<String> reduced =
        stringCollection
                .stream()
                .sorted()
                .reduce((s1, s2) -> s1 + "#" + s2);
複製代碼

parallelStream

並行的 steam 流,能夠進行並行處理,這樣會效率更高。在使用stream.foreach時這個遍歷沒有線程安全問題,可是使用parallelStream就會有線程安全問題,全部在parallelStream裏面使用的外部變量,好比集合必定要使用線程安全集合,否則就會引起多線程安全問題。若是說須要保證安全性須要使用 reduce 和 collect,不過這個用起來超級麻煩!!!

long count = values.parallelStream().sorted().count();
複製代碼

IntStream.range(a,b)

能夠直接生成 從 a 到 b 的整數這裏仍是遵循編程語言的大多數約定,那就是含頭不含尾。

IntStream.range(0, 10)
    .forEach(System.out::println);
複製代碼

輸出的結果是

0
1
2
3
4
5
6
7
8
9
複製代碼

new Random().ints()

獲取一系列的隨機值,這個接口出來的數據是接二連三的,因此須要用limit來限制一下。

new Random().ints().limit(10).forEach(System.out::println);
複製代碼

Supplier

Supplier<String> stringSupplier=String::new;
stringSupplier.get();
複製代碼

該接口就一個抽象方法get方法,不用傳入任何參數,直接返回一個泛型T的實例.就如同無參構造同樣

Consumer

1. accept方法

​ 該函數式接口的惟一的抽象方法,接收一個參數,沒有返回值.

2. andThen方法

​ 在執行完調用者方法後再執行傳入參數的方法.

public class ConsumerTest {
    public static void main(String[] args) {
        Consumer<Integer> consumer = (x) -> {
            int num = x * 2;
            System.out.println(num);
        };
        Consumer<Integer> consumer1 = (x) -> {
            int num = x * 3;
            System.out.println(num);
        };
        consumer.andThen(consumer1).accept(10);
    }
複製代碼

先執行了 consumer.accept(10) 而後執行了 consumer1.accept(10)

ifPresent

針對一個optional 若是有值的話就執行不然不執行。

IntStream
    .builder()
    .add(1)
    .add(3)
    .add(5)
    .add(7)
    .add(11)
    .build()
    .average()
    .ifPresent(System.out::println);
複製代碼

average 執行結果就是一個 optional

Collect

他有兩種調用方式

<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner);

 <R, A> R collect(Collector<? super T, A, R> collector);
複製代碼

下面主要介紹一下這兩種方式的使用方法:

1. 函數

第一種調用方式的接口以下

<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner);
複製代碼
  • supplier 這個參數就是提供一個容器,能夠看到最後 collect 操做的結果是一個 R 類型變量,而 supplier 接口最後須要返回的也是一個 R 類型的變量,因此說這裏返回的是收集元素的容器。
  • accumulator 參數,看到這個函數的定義是傳入一個 R 容器,後面則是 T 類型的元素,須要將這個 T 放到 R 容器中,即這一步是用來將元素添加到容器中的操做。
  • conbiner 這個參數是兩個容器,即當出現多個容器的時候容器如何進行聚合。

一個簡單的例子:

String concat = stringStream.collect(StringBuilder::new, StringBuilder::append,StringBuilder::append).toString();
//等價於上面,這樣看起來應該更加清晰
String concat = stringStream.collect(() -> new StringBuilder(),(l, x) -> l.append(x), (r1, r2) -> r1.append(r2)).toString();
複製代碼

2. Collector 接口

第二種方案是更高級的用法採用了 Collector 接口:

<R, A> R collect(Collector<? super T, A, R> collector);
複製代碼

能夠看到他返回的仍是一個 R 類型的變量,也就是容器。

Collector接口是使得collect操做強大的終極武器,對於絕大部分操做能夠分解爲旗下主要步驟,提供初始容器->加入元素到容器->併發下多容器聚合->對聚合後結果進行操做

static class CollectorImpl<T, A, R> implements Collector<T, A, R> {
        private final Supplier<A> supplier;
        private final BiConsumer<A, T> accumulator;
        private final BinaryOperator<A> combiner;
        private final Function<A, R> finisher;
        private final Set<Characteristics> characteristics;

        CollectorImpl(Supplier<A> supplier,
                      BiConsumer<A, T> accumulator,
                      BinaryOperator<A> combiner,
                      Function<A,R> finisher,
                      Set<Characteristics> characteristics) {
            this.supplier = supplier;
            this.accumulator = accumulator;
            this.combiner = combiner;
            this.finisher = finisher;
            this.characteristics = characteristics;
        }

        CollectorImpl(Supplier<A> supplier,
                      BiConsumer<A, T> accumulator,
                      BinaryOperator<A> combiner,
                      Set<Characteristics> characteristics) {
            this(supplier, accumulator, combiner, castingIdentity(), characteristics);
        }

        @Override
        public BiConsumer<A, T> accumulator() {
            return accumulator;
        }

        @Override
        public Supplier<A> supplier() {
            return supplier;
        }

        @Override
        public BinaryOperator<A> combiner() {
            return combiner;
        }

        @Override
        public Function<A, R> finisher() {
            return finisher;
        }

        @Override
        public Set<Characteristics> characteristics() {
            return characteristics;
        }
    }
複製代碼

能夠看到咱們能夠直接 new CollectorImpl 而後將這些函數傳入,另外還有一種簡單的方式就是 使用 Collector.of()依然能夠直接傳入函數。和 new CollectorImpl 是等價的。

3. 工具函數

1. toList()

容器: ArrayList::new 加入容器操做: List::add 多容器合併: left.addAll(right); return left;

public static <T>
    Collector<T, ?, List<T>> toList() {
        return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
                                   (left, right) -> { left.addAll(right); return left; },
                                   CH_ID);
    }
複製代碼

2.joining()

容器: StringBuilder::new 加入容器操做: StringBuilder::append 多容器合併: r1.append(r2); return r1; 聚合後的結果操做: StringBuilder::toString

public static Collector<CharSequence, ?, String> joining() {
        return new CollectorImpl<CharSequence, StringBuilder, String>(
                StringBuilder::new, StringBuilder::append,
                (r1, r2) -> { r1.append(r2); return r1; },
                StringBuilder::toString, CH_NOID);
    }
複製代碼

3.groupingBy()

roupingBytoMap的一種高級方式,彌補了toMap對值沒法提供多元化的收集操做,好比對於返回Map<T,List<E>>這樣的形式toMap就不是那麼順手,那麼groupingBy的重點就是對Key和Value值的處理封裝.分析以下代碼,其中classifier是對key值的處理,mapFactory則是指定Map的容器具體類型,downstream爲對Value的收集操做.

public static <T, K, D, A, M extends Map<K, D>>
    Collector<T, ?, M> groupingBy(Function<? super T, ? extends K> classifier,
                                  Supplier<M> mapFactory,
                                  Collector<? super T, A, D> downstream) {
       .......
    }
複製代碼

一個簡單的例子

//原生形式
   Lists.<Person>newArrayList().stream()
        .collect(() -> new HashMap<Integer,List<Person>>(),
            (h, x) -> {
              List<Person> value = h.getOrDefault(x.getType(), Lists.newArrayList());
              value.add(x);
              h.put(x.getType(), value);
            },
            HashMap::putAll
        );
//groupBy形式
Lists.<Person>newArrayList().stream()
        .collect(Collectors.groupingBy(Person::getType, HashMap::new, Collectors.toList()));
//由於對值有了操做,所以我能夠更加靈活的對值進行轉換
Lists.<Person>newArrayList().stream()
        .collect(Collectors.groupingBy(Person::getType, HashMap::new, Collectors.mapping(Person::getName,Collectors.toSet())));
// 還有一種比較簡單的使用方式 只須要傳遞一個參數按照key來劃分
Map<Integer, List<Person>> personsByAge = persons
            .stream()
    .collect(Collectors.groupingBy(p -> p.age));
複製代碼

4.reducing()

reducing是針對單個值的收集,其返回結果不是集合家族的類型,而是單一的實體類T 容器: boxSupplier(identity),這裏包裹用的是一個長度爲1的Object[]數組,至於緣由天然是不可變類型的鍋 加入容器操做: a[0] = op.apply(a[0], t) 多容器合併: a[0] = op.apply(a[0], b[0]); return a; 聚合後的結果操做: 結果天然是Object[0]所包裹的數據a -> a[0] 優化操做狀態字段: CH_NOID

public static <T> Collector<T, ?, T>
    reducing(T identity, BinaryOperator<T> op) {
        return new CollectorImpl<>(
                boxSupplier(identity),
                (a, t) -> { a[0] = op.apply(a[0], t); },
                (a, b) -> { a[0] = op.apply(a[0], b[0]); return a; },
                a -> a[0],
                CH_NOID);
    }
複製代碼

簡單來講這個地方作的事情和 reduce 是同樣的,第一個 id 傳入的就是 reduce 的初始值,只是他把它包裝成一個 長度爲1的數組了。

//原生操做
final Integer[] integers = Lists.newArrayList(1, 2, 3, 4, 5)
        .stream()
        .collect(() -> new Integer[]{0}, (a, x) -> a[0] += x, (a1, a2) -> a1[0] += a2[0]);
//reducing操做
final Integer collect = Lists.newArrayList(1, 2, 3, 4, 5)
        .stream()
        .collect(Collectors.reducing(0, Integer::sum));    
//固然Stream也提供了reduce操做
final Integer collect = Lists.newArrayList(1, 2, 3, 4, 5)
        .stream().reduce(0, Integer::sum)
複製代碼
相關文章
相關標籤/搜索