篩選和切片
篩選
// 篩選蔬菜
List<Dish> vegetarianMenu = menu.stream().filter(Dish::isVegetarian).collect(toList());
排重
// 列出所有偶數(shù)排重
numbers.stream().filter(i -> i%2 ==0).distinct().forEach(...);
截斷
// 取前3個成員
menu.stream().limit(3).collect(...);
跳過元素
// 跳過前2個成員
menu.stream().skip(2).collect(...);
映射
對流中每一個元素應(yīng)用函數(shù)
// 提取每道菜名稱的長度
menu.stream().map(Dish::getName).map(String::length).collect(...);
流的扁平化
words.stream().map(w->w.split("") // 單詞轉(zhuǎn)換成字母構(gòu)成的數(shù)組
.flatMap(Arrays::stream) // 扁平化 (相當(dāng)于把數(shù)組拆成一個個元素,沒有數(shù)組和數(shù)組之間結(jié)構(gòu)之分)
.distinct().collect(...);
查找和匹配
至少匹配一個元素
// 集合里有一個元素都滿足液样,就返回true
if (menu.stream().anyMatch(Dish::isVegetarian)) {
...
}
匹配所有元素
isHealthy = menu.stream().allMatch(d -> d.getCalories() < 1000);
// 相對的篇亭,確保流中沒有任何元素與給定的謂詞匹配
isHealthy = menu.stream().noneMatch(d -> d.getCalories() >= 1000);
查找元素
// 找到流中的任意一道素菜
Optional<Dish> dish = menu.stream().filter(Dish::isVegetarian).findAny();
查找第一個元素
// findFirst在并行上限制更多,findAny限制少争舞,前提是你不關(guān)心返回的元素是哪個
someNumbers.stream().filter(x->x%3 ==0).findFirst();
歸約
求和
numbers.stream().reduce(0, (a, b) -> a+b);
最大值和最小值
numbers.stream().reduce((x,y) -> x<y?x:y);
數(shù)值流
原始類型流特化
// 數(shù)值流
// mapToInt將Stream<Integer>轉(zhuǎn)換成IntStrem,就可以調(diào)用特有的sum等方法了
menu.stream().mapToInt(Dish::getCalories).sum();
// boxed轉(zhuǎn)化回對象流
intStream().boxed();
構(gòu)建流
由值創(chuàng)建流
Stream<String> stream = Stream.of("...", "...");
由數(shù)組創(chuàng)建流
// int數(shù)組直接轉(zhuǎn)換成IntStream()
Arrays.stream(numbers).sum();
由文件生成流
Stream<String> lines = Files.lines(Paths.get("data.txt"),Charset.defaultCharset());