規(guī)約操作
規(guī)約操作:通過某個(gè)連接動(dòng)作將所有元素匯總成一個(gè)結(jié)果的過程配乱。元素求和拐纱、求最大值或最小值泵督、求出元素總個(gè)數(shù)趾盐、將所有元素轉(zhuǎn)換成一個(gè)列表或集合,都屬于規(guī)約操作。
Stream類庫有兩個(gè)通用的規(guī)約操作reduce()和collect()救鲤。還有專用規(guī)約操作:sum()久窟、max()、min()本缠、count()等
reduce()
reduce實(shí)現(xiàn)從一組元素中生成一個(gè)值斥扛。
Optional<T> reduce(BinaryOperator<T> accumulator);
T reduce(T identity, BinaryOperator<T> accumulator)丹锹;
<U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)稀颁;
identity:初始值;accumulator:收集規(guī)則(累加楣黍,長(zhǎng)度等)匾灶;combiner:并行執(zhí)行時(shí)多個(gè)部分結(jié)果的合并方式。
reduce()常用的場(chǎng)景是從一堆值中生成一個(gè)值租漂。
collect()
實(shí)例:
Stream<String> stream = Stream.of("","","");
List<String> list = stream.collect(Collectors.toList());
Set<String> set = stream.collect(Collectors.toSet());
Map<String, Integer> map = stream.collect(Collectors.toMap(Function.identity(), String::length));
將Stream轉(zhuǎn)換成List阶女,Set或是Map。
Function
@FunctionalInterfacepublic interface Function<T, R> { R apply(T t); default <V> Function<V, R> compose(Function<? super V, ? extends T> before) { Objects.requireNonNull(before); return (V v) -> apply(before.apply(v)); } default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) { Objects.requireNonNull(after); return (T t) -> after.apply(apply(t)); } static <T> Function<T, T> identity() { return t -> t; }}
收集器(Collector)
收集器是為了Stream.collect()方法打造的工具接口哩治。我們將Stream轉(zhuǎn)換成集合或是Map秃踩,需要知道1,目標(biāo)容器是什么业筏?2憔杨,新元素如何添加到集合中?3蒜胖,如果進(jìn)行并行規(guī)約芍秆,多個(gè)部分結(jié)果如何合并成一個(gè)。
Stream.collect的方法定義:
<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner);
里面的三個(gè)參數(shù)分別對(duì)應(yīng)上面的三個(gè)問號(hào)翠勉。這個(gè)方法可以收集任何形式你想要的信息,還有一個(gè)collect方法是對(duì)這三個(gè)參數(shù)的封裝霉颠。
<R, A> R collect(Collector<? super T, A, R> collector);
Collectors類通過靜態(tài)方法生成各種常用的收集器(Collector)对碌,Collectors.toList()返回生成List的收集器。Collectors.toMap()返回生成Map的收集器蒿偎。
Collectors.toCollection(ArrayList::new)可以指定集合的具體類型
ArrayList<String> arrayList = stream.collect(Collectors.toCollection(ArrayList::new));
現(xiàn)在重點(diǎn)說說生成map收集器
前面說Stream依賴數(shù)據(jù)源朽们,數(shù)據(jù)源可以是數(shù)組,集合等诉位。但是不會(huì)是map骑脱。但是我們可以從Stream生成Map。
1苍糠,Collectors.toMap():生成收集器叁丧,需要指定如何生成Map的key和value。
2,Collectors.partitioningBy():生成收集器拥娄,對(duì)元素進(jìn)行二分區(qū)操作蚊锹。依據(jù)某個(gè)條件分成兩部分(滿足條件和不滿足條件)
3,Collectors.groupingBy():生成收集器稚瘾,對(duì)元素做group操作牡昆。按照某個(gè)屬性對(duì)元素進(jìn)行分組,屬性相同的元素被對(duì)應(yīng)到map的同一個(gè)key上摊欠。groupingBy還運(yùn)行對(duì)元素進(jìn)行分組后再執(zhí)行運(yùn)算(求和丢烘,類型轉(zhuǎn)換等操作)。先將元素分組的收集器叫做上游收集器些椒,之后執(zhí)行其他運(yùn)算的收集器叫做下游收集器播瞳。
字符串拼接
字符串拼接時(shí)使用Collectors.joining()生成的收集器。
1摊沉,Stream.collect(Collectors.joining())狐史。
2,Stream.collect(Collectors.joining(","))说墨。// 按照逗號(hào)分隔符拼接字符串
3骏全,Stream.collect(Collectors.joining(",","{","}"))。// 按照逗號(hào)分隔符拼接字符串尼斧,在最前端加“{”姜贡,在字符串末尾加“}”。