authors.stream().map(new Function<Author, Integer>() {
@Override
public Integer apply(Author author) {
return author.getAge()+10;
}
}).forEach(System.out::println);
distinct
可以去除流中的重复元素
注意:distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以需要注意equals方法。
sorted
重载的两个方法:
无参数sorted()
- 需要实现Comparable接口
- 重写compareTo方法
public class Author implements Comparable<Author>{
@Override
public int compareTo(Author o) {
return this.getAge()-o.getAge();
}
有参数Sorted()
public static void testThree(){
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.sorted(new Comparator<Author>() {
@Override
public int compare(Author o1, Author o2) {
return o1.getAge()-o2.getAge();
}
})
.forEach(author -> System.out.println(author.getAge()));
}
limit
可以设置流的最大长度,超出的部分将被抛弃
// 打印其中年龄最大的两个作家的姓名
authors.stream()
.distinct()
.sorted(new Comparator<Author>() {
@Override
public int compare(Author o1, Author o2) {
return o2.getAge()-o1.getAge();
}
})
.limit(2)
.forEach(System.out::println);
skip
跳过流中的前n个元素,返回剩下的元素
flatMap
map只能把一个对象转成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素
可以把集合中的元素转为一个个对象类型来操作
List<Author> authors = getAuthors();
// 打印现有数据的所有分类
authors.stream()
.flatMap( author -> author.getBooks().stream())
.distinct()
.flatMap( book -> Arrays.stream(book.getCategory().split(",")))
.distinct()
.forEach(System.out::println);
重载的两个方法:
无参数sorted()
- 需要实现Comparable接口
- 重写compareTo方法
public class Author implements Comparable<Author>{
@Override
public int compareTo(Author o) {
return this.getAge()-o.getAge();
}
有参数Sorted()
public static void testThree(){
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.sorted(new Comparator<Author>() {
@Override
public int compare(Author o1, Author o2) {
return o1.getAge()-o2.getAge();
}
})
.forEach(author -> System.out.println(author.getAge()));
}
limit
可以设置流的最大长度,超出的部分将被抛弃
// 打印其中年龄最大的两个作家的姓名
authors.stream()
.distinct()
.sorted(new Comparator<Author>() {
@Override
public int compare(Author o1, Author o2) {
return o2.getAge()-o1.getAge();
}
})
.limit(2)
.forEach(System.out::println);
skip
跳过流中的前n个元素,返回剩下的元素
flatMap
map只能把一个对象转成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素
可以把集合中的元素转为一个个对象类型来操作
List<Author> authors = getAuthors();
// 打印现有数据的所有分类
authors.stream()
.flatMap( author -> author.getBooks().stream())
.distinct()
.flatMap( book -> Arrays.stream(book.getCategory().split(",")))
.distinct()
.forEach(System.out::println);