StreamMatch 匹配
anyMatch表示,判断的条件里,任意一个元素成功,返回true
allMatch表示,判断条件里的元素,所有的都是,返回true
noneMatch跟allMatch相反,判断条件里的元素,所有的都不是,返回true
Stream<Student> stream = students.stream();
//anyMatch表示,判断的条件里,任意一个元素成功,返回true
boolean result = stream.anyMatch(new Predicate<Student>() {
@Override
public boolean test(Student student) {
return student.getAge() ==8 ;
}
});
//lambda
boolean result1 = stream.anyMatch((user) -> user.getAge() ==9 );
System.out.println(result);
System.out.println(result1);
将集合对象的某个字段取出转成string 集合
List<String> collect = stream.map(Student::getName).collect(Collectors.toList());
System.out.println(collect);
遍历 forEach
Stream<Student> stream = students.stream();
// stream.forEach(new Consumer<Student>() {
// @Override
// public void accept(Student student) {
// System.out.println(student.toString());
// }
// });
//lambda
stream.forEach(( s->
System.out.println(s.toString())
));
过滤器 filter
Stream<Student> stream = students.stream();
// stream.filter(new Predicate<Student>() {
// @Override
// public boolean test(Student student) {
// return student.getAge() >= 3;
// }
// }).filter(new Predicate<Student>() {
// @Override
// public boolean test(Student student) {
// return student.getName().equals("小红");
// }
// }).forEach(new Consumer<Student>() {
// @Override
// public void accept(Student student) {
// System.out.println(student.toString());
// }
// });
//lambda
stream.filter(student -> student.getName().contains("小"))
.filter(student -> student.getAge()>2).forEach(student -> System.out.println(student));
排序 sorted
Stream<Student> stream = students.stream();
// stream.sorted(new Comparator<Student>() {
// @Override
// public int compare(Student o1, Student o2) {
// return o1.getAge() - o2.getAge();
// }
// }).forEach(new Consumer<Student>() {
// @Override
// public void accept(Student student) {
// System.out.println(student.toString());
// }
// });
//lambda
stream.sorted(((o1, o2) -> o2.getAge() - o1.getAge()))
.forEach(student -> System.out.println(student));
limit和skip
Stream<Student> stream = students.stream();
stream.skip(2).limit(1).forEach(student -> System.out.println(student));