學(xué)習(xí)札記-Java8系列-10-詳解Stream操作
操作步驟
使用Stream API操作數(shù)據(jù)可以分為以下幾個(gè)步驟:
1)創(chuàng)建流:
通過(guò)數(shù)據(jù)源(如:集合邀层、數(shù)組)獲取流
2)處理流:(中的數(shù)據(jù))
對(duì)流中的數(shù)據(jù)進(jìn)行處理(處理是延遲執(zhí)行的)
3)收集流:(中的數(shù)據(jù))
通過(guò)調(diào)用收集方法椭员,真正執(zhí)行處理操作,并產(chǎn)生結(jié)果
創(chuàng)建流
創(chuàng)建一個(gè)流非常簡(jiǎn)單锁孟,有以下幾種常用的方式:
1)Collection的默認(rèn)方法stream()和parallelStream()
2)Arrays.stream()
3)Stream.of()
4)Stream.iterate()//迭代無(wú)限流(1, n->n +1)
5)Stream.generate()//生成無(wú)限流(Math::random)
代碼實(shí)現(xiàn)
@Test
public void testCreateStream() throws Exception {
// 1.Collection的默認(rèn)方法stream()和parallelStream()
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();// 獲取順序流
Stream<String> parallelStream = list.parallelStream();
// 2.Arrays.stream()
IntStream intStream = Arrays.stream(new int[] { 1, 2, 3 });
Stream<Integer> IntegerStream = Arrays.stream(new Integer[] { 1, 2, 3 });
// 3.Stream.of()
Stream<Integer> IntegerStream2 = Stream.of(1, 2, 3, 4);
IntStream intStream2 = IntStream.of(1, 2, 3);
// 4.Stream.iterate()//迭代無(wú)限流
// Stream.iterate(1, n->n +1).forEach(System.out::println);
Stream.iterate(1, n -> n + 1).limit(100).forEach(System.out::println);
// 5.Stream.generate()//生成無(wú)限流
// Stream.generate(Math::random).forEach(System.out::println);
Stream.generate(Math::random).limit(2).forEach(System.out::println);
}
處理流
篩選和切片
filter(Predicate<T> p):過(guò)濾(根據(jù)傳入的Lambda返回的ture/false 從流中過(guò)濾掉某些數(shù)據(jù)(篩選出某些數(shù)據(jù)))
distinct():去重(根據(jù)流中數(shù)據(jù)的 hashCode和 equals去除重復(fù)元素)
limit(long n):限定保留n個(gè)數(shù)據(jù)
skip(long n):跳過(guò)n個(gè)數(shù)據(jù)
圖解
代碼實(shí)現(xiàn)
@Test
public void test1() throws Exception {
Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().filter(i -> i % 2 == 0).forEach(System.out::println);
System.out.println("================================================");
Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);
System.out.println("================================================");
Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().distinct().limit(2).forEach(System.out::println);
System.out.println("================================================");
Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().distinct().skip(2).forEach(System.out::println);
}
映射
映射
map(Function<T, R> f):接收一個(gè)函數(shù)作為參數(shù)孽尽,該函數(shù)會(huì)被應(yīng)用到流中的每個(gè)元素上浩嫌,并將其映射成一個(gè)新的元素超歌。
flatMap(Function<T, Stream<R>> mapper):接收一個(gè)函數(shù)作為參數(shù),將流中的每個(gè)值都換成另一個(gè)流卖鲤,然后把所有流連接成一個(gè)流
圖解
代碼實(shí)現(xiàn)
@Test
public void test3() throws Exception {
System.out.println("=======================map=========================");
Stream<String> stream = Stream.of("i","love","java");
stream.map(s -> s.toUpperCase()).forEach(System.out::println);
System.out.println("=======================flatMap========================");
Stream<List<String>> stream2 = Stream.of(Arrays.asList("H","E"), Arrays.asList("L", "L", "O"));
stream2.flatMap(list -> list.stream()).forEach(System.out::println);
}
排序
排序
sorted():自然排序使用Comparable<T>的int compareTo(T o)方法
sorted(Comparator<T> com):定制排序使用Comparator的int compare(T o1, T o2)方法
代碼實(shí)現(xiàn)
@Test
public void test4() throws Exception {
System.out.println("====================自然排序============================");
Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().sorted().forEach(System.out::println);
System.out.println("====================定制排序============================");
Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().sorted((x,y) -> y.compareTo(x)).forEach(System.out::println);
}
收集流
查找匹配
查找匹配
allMatch:檢查是否匹配所有元素
anyMatch:檢查是否至少匹配一個(gè)元素
noneMatch:檢查是否沒(méi)有匹配的元素
findFirst:返回第一個(gè)元素(返回值為Optional<T>)
findAny:返回當(dāng)前流中的任意元素(一般用于并行流)
備注:
Optional<T>是Java8新加入的一個(gè)容器肾扰,這個(gè)容器只存1個(gè)或0個(gè)元素,它用于防止出現(xiàn)NullpointException蛋逾,它提供如下方法:
?isPresent()
判斷容器中是否有值集晚。
?ifPresent(Consume lambda)
容器若不為空則執(zhí)行括號(hào)中的Lambda表達(dá)式。
?T get()
獲取容器中的元素换怖,若容器為空則拋出NoSuchElement異常甩恼。
?T orElse(T other)
獲取容器中的元素,若容器為空則返回括號(hào)中的默認(rèn)值沉颂。
代碼實(shí)現(xiàn)
@Test
public void test5() throws Exception {
System.out.println("======================檢查是否匹配所有==========================");
boolean allMatch = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().allMatch(x-> x>0);
System.out.println(allMatch);
System.out.println("======================檢查是否至少匹配一個(gè)元素====================");
boolean anyMatch = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().anyMatch(x -> x>7);
System.out.println(anyMatch);
System.out.println("======================檢查是否沒(méi)有匹配的元素======================");
boolean noneMatch = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().noneMatch(x -> x >10);
System.out.println(noneMatch);
System.out.println("======================返回第一個(gè)元素==========================");
Optional<Integer> first = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().findFirst();
System.out.println(first.get());
System.out.println("======================返回當(dāng)前流中的任意元素=======================");
Optional<Integer> any = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().findAny();
System.out.println(any.get());
}
統(tǒng)計(jì)
統(tǒng)計(jì)
count():返回流中元素的總個(gè)數(shù)
max(Comparator<T>):返回流中最大值
min(Comparator<T>):返回流中最小值
代碼實(shí)現(xiàn)
@Test
public void test6() throws Exception {
long count = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().count();
System.out.println(count);
Optional<Integer> max = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().max((x,y) -> x.compareTo(y));
System.out.println(max.get());
Optional<Integer> min = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().min((x,y) -> x.compareTo(y));
System.out.println(min.get());
}
歸約
歸約
reduce(T identity, BinaryOperator) / reduce(BinaryOperator) :將流中元素挨個(gè)結(jié)合起來(lái)条摸,得到一個(gè)值。
圖解
代碼實(shí)現(xiàn)
@Test
public void test7() throws Exception {
System.out.println("=====reduce:將流中元素反復(fù)結(jié)合起來(lái)铸屉,得到一個(gè)值==========");
Stream<Integer> stream = Stream.iterate(1, x -> x+1).limit(100);
//stream.forEach(System.out::println);
Integer sum = stream.reduce(0,(x,y)-> x+y);
System.out.println(sum);
}
匯總
匯總
reduce擅長(zhǎng)的是生成一個(gè)值钉蒲,如果想要從Stream生成一個(gè)集合或者M(jìn)ap等復(fù)雜的對(duì)象該怎么辦呢?終極武器collect()橫空出世彻坛!
collect(Collector<T, A, R>):將流轉(zhuǎn)換為其他形式顷啼。
需求:
collect:將流轉(zhuǎn)換為其他形式:list
collect:將流轉(zhuǎn)換為其他形式:set
collect:將流轉(zhuǎn)換為其他形式:TreeSet
collect:將流轉(zhuǎn)換為其他形式:map
collect:將流轉(zhuǎn)換為其他形式:sum
collect:將流轉(zhuǎn)換為其他形式:avg
collect:將流轉(zhuǎn)換為其他形式:max
collect:將流轉(zhuǎn)換為其他形式:min
代碼實(shí)現(xiàn)
@Test
public void test8() throws Exception {
System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:list");
List<Integer> list = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.toList());
System.out.println(list);
System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:set");
Set<Integer> set = Arrays.asList(1, 1, 2, 2, 3, 3, 3).stream().collect(Collectors.toSet());
System.out.println(set);
System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:TreeSet");
TreeSet<Integer> treeSet = Arrays.asList(1, 1, 2, 2, 3, 3, 3).stream().collect(Collectors.toCollection(TreeSet::new));
System.out.println(treeSet);
System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:map");
Map<Integer, Integer> map = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.toMap(Integer::intValue, Integer::intValue));
System.out.println(map);
System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:sum");
Integer sum = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.summingInt(Integer::intValue));
System.out.println(sum);
System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:avg");
Double avg = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.averagingInt(Integer::intValue));
System.out.println(avg);
System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:max");
Optional<Integer> max = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.maxBy(Integer::compareTo));
System.out.println(max.get());
System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:min");
Optional<Integer> min = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.minBy((x,y) -> x-y));
System.out.println(min.get());
}
分組和分區(qū)
分組和分區(qū)
Collectors.groupingBy()對(duì)元素做group操作。
Collectors.partitioningBy()對(duì)元素進(jìn)行二分區(qū)操作昌屉。
圖解
準(zhǔn)備工作
private List<Product> products = new ArrayList<>();
@Before
public void init() {
products.add(new Product(1L, "蘋果手機(jī)", 8888.88,"手機(jī)"));//注意:要給Product類加一個(gè)分類名稱dirName字段
products.add(new Product(2L, "華為手機(jī)", 6666.66,"手機(jī)"));
products.add(new Product(3L, "聯(lián)想筆記本", 7777.77,"電腦"));
products.add(new Product(4L, "機(jī)械鍵盤", 999.99,"鍵盤"));
products.add(new Product(5L, "雷蛇鼠標(biāo)", 222.22,"鼠標(biāo)"));
}
需求
根據(jù)商品分類名稱進(jìn)行分組
根據(jù)商品價(jià)格范圍多級(jí)分組
根據(jù)商品價(jià)格是否大于1000進(jìn)行分區(qū)
代碼實(shí)現(xiàn)
@Test
public void test9() throws Exception {
System.out.println("=======根據(jù)商品分類名稱進(jìn)行分組==========================");
Map<String, List<Product>> map = products.stream().collect(Collectors.groupingBy(Product::getDirName));
System.out.println(map);
System.out.println("=======根據(jù)商品價(jià)格范圍多級(jí)分組==========================");
Map<Double, Map<String, List<Product>>> map2 = products.stream().collect(Collectors.groupingBy(
Product::getPrice, Collectors.groupingBy((p) -> {
if (p.getPrice() > 1000) {
return "高級(jí)貨";
} else {
return "便宜貨";
}
})));
System.out.println(map2);
}
@Test
public void test10() throws Exception {
System.out.println("========根據(jù)商品價(jià)格是否大于1000進(jìn)行分區(qū)========================");
Map<Boolean, List<Product>> map = products.stream().collect(Collectors.partitioningBy(p -> p.getPrice() > 1000));
System.out.println(map);
}
總結(jié)
Streamvs Collection
雖然大部分情況下Stream是容器調(diào)用Collection.stream()方法得到的钙蒙,但Stream和Collection有以下不同:
●無(wú)存儲(chǔ)。Stream不是一種數(shù)據(jù)結(jié)構(gòu)间驮,它只是某種數(shù)據(jù)源的一個(gè)視圖躬厌,數(shù)據(jù)源可以是一個(gè)數(shù)組,集合等竞帽。
●不修改扛施。對(duì)Stream的任何修改都不會(huì)修改背后的數(shù)據(jù)源,比如過(guò)濾操作并不會(huì)刪除被過(guò)濾的元素屹篓,而是產(chǎn)生一個(gè)新Stream疙渣。
●惰式執(zhí)行。Stream上的操作并不會(huì)立即執(zhí)行堆巧,只有等到用戶真正需要結(jié)果的時(shí)候才會(huì)執(zhí)行妄荔。
●可消費(fèi)性泼菌。Stream只能被“消費(fèi)”一次,一旦遍歷過(guò)就會(huì)失效懦冰,就像容器的迭代器那樣灶轰,想要再次遍歷必須重新生成谣沸。
Stream分類
●中間操作(intermediate operations)
返回值為Stream的大都是中間操作刷钢,中間操作支持鏈?zhǔn)秸{(diào)用,并且會(huì)惰式執(zhí)行
●終端操作(結(jié)束操作)(terminal operations)
返回值不為Stream 的為終端操作(立即求值)乳附,終端操作不支持鏈?zhǔn)秸{(diào)用内地,會(huì)觸發(fā)實(shí)際計(jì)算