Stream流
- Java 8 API添加了一个新的抽象称为流Stream,可以让你以一种声明的方式处理数据。
- Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。
- ==只能用于Collection的集合==
使用的几个场景
Person类
public class Person {
int age;
String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 6);
Stream stream = list.stream().distinct();
stream.forEach(p -> System.out.println(p));
- 去重并替代元素map(把person替换为里面的名字)
List<Person> list = new ArrayList<>();
list.add(new Person(1, "A"));
list.add(new Person(2, "B"));
list.add(new Person(3, "C"));
list.add(new Person(4, "D"));
list.add(new Person(5, "E"));
list.add(new Person(5, "E"));
list.stream().
distinct()
.map(p -> p.getName())
.forEach(c -> System.out.println("名字为:" + c));
List<Person> list = new ArrayList<>();
list.add(new Person(1, "A"));
list.add(new Person(2, "B"));
list.add(new Person(3, "C"));
list.add(new Person(4, "D"));
list.add(new Person(5, "E"));
list.add(new Person(5, "E"));
//Function<? super T, ? extends R> function = ;
list.stream()
.filter(person -> person.getAge() >= 3)
.distinct()
.map(person -> person.getName()).forEach(name -> System.out.println(name));
- 取集合前面三个值,用name代替person,并且排序
List<Person> list = new ArrayList<>();
list.add(new Person(1, "A"));
list.add(new Person(2, "B"));
list.add(new Person(3, "C"));
list.add(new Person(4, "D"));
list.add(new Person(5, "E"));
list.add(new Person(5, "E"));
//Function<? super T, ? extends R> function = ;
list.stream()
.filter(person -> person.getAge() >= 3)
.distinct()
.limit(3)
.map(person -> person.getName())
.sorted()
.forEach(name -> System.out.println(name));