案例来自于Java8 实战.
Raoul-Gabriel Urma, Mario Fusco, Alan Mycroft, Java 8 in Action[M], Manning Publications, 2014
流操作
流允许你以声明式方式处理数据集合(通过类似于查询语句的方式来表达), 其内部可以透明地并行处理.Java 8中的集合支持一个新的stream方法,它会返回一个流(接口定义在java.util.stream.Stream里).
注意: 流只能遍历一次!
筛选和切片
Streams接口的filter方法接受一个返回boolean的函数用于筛选, distinct()方法返回一个元素各异的流, limit(n)返回前n个元素, skip(n)忽略流中的头n个元素.
例如筛选各异的偶数:
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
numbers.stream()
.filter(i -> i % 2 == 0)
.distinct()
.forEach(System.out::println);
选出热量超过300卡路里的头3道菜:
List<Dish> dishes = menu.stream()
.filter(d -> d.getCalories() > 300)
.limit(3)
.collect(toList());
跳过热量超过300卡路里的头两到菜,返回剩下的. skip(n)与limit(n)互补, 如果不足n则返回空集.
List<Dish> dishes = menu.stream()
.filter(d -> d.getCalories() > 300)
.skip(2)
.collect(toList());
映射
流支持map方法, 它会接受一个函数, 这个函数会应用到每一个元素上并将其映射为一个新的元素. flatMap方法则将各个流合并成单个流.
例如提取流中菜肴的名称:
List<String> dishNames = menu.stream()
.map(Dish::getName)
.collect(toList());
返回单词集合中所有单词的长度:
List<String> words = Arrays.asList("Java 8", "Lambdas", "In", "Action");
List<Integer> wordLengths = words.stream()
.map(String::length)
.collect(toList());
给定一个单词集合, 返回该集合中所有不同字符列表.
// wrong
words.stream()
.map(word -> word.split("")) // 对于每个单词返回一个String[]
.distinct()
.collect(toList());
// wrong
words.stream()
.map(word -> word.split(""))
.map(Arrays::stream) // 将每个单词对应的String[]分别映射为Stream<String>
.distinct()
.collect(toList())