Stream简介
Java8中的Stream是对与集合对象有所加强的新特性,专注于集合对象进行各种非常便利,高效的聚合操作,同时提供串行与并行两种模式的汇聚操作,使用了fork/join并行方式来拆分任务、加速处理过程。注意,这里的stream与原先的文件I/O流没有必然关系,是在Java8中的新内容。
准备:
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person{
String name;
String com;
Integer age;
Integer house;
}
一、集合遍历
@Test // 遍历集合
public void testName() throws Exception {
List<Person> peoples = new ArrayList<>(Arrays.asList(
new Person("name1",12),
new Person("name2",13),
new Person("name2",14),
new Person("name3",15)
));
// 传统增强for
for (Person people : peoples) {
System.out.println(people.getName());
}
// 新特性: ForEach
peoples.forEach(people-> System.out.println(people.getName()));
}
二、过滤年龄小于15的人
// 获取所有年龄大于 15 的人
List<Person> person = peoples.stream().filter(person -> person.getAge() >= 15).collect(toList());
三、过滤获取属性
// 获取所有人名
List<String> name = peoples.stream().map(Person::getName).collect(toList());
四、分组统计
// 这样我们就得到了一个以年龄为key,以这个年龄的人数为value的map了,还有很多其他的方法
Map<Integer,Long> personGroups = peoples.stream().collect()(groupingBy(Person::getAge,counting()));