Stream<Integer> stream = Stream.of(11, 22, 33, 44, 55);
long count = stream.count();
System.out.println(count); //5
Stream<Integer> stream = Stream.of(11, 22, 33, 44, 55);
//遍历流中的数据
//匿名内部类
stream.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer integer) {
System.out.println(integer);
}
});
forEach里面是一个"Consumer函数式接口",每次使用可以先new这个接口出来,再对应使用Lambda简化
Stream<Integer> stream = Stream.of(11, 22, 33, 44, 55,66);
Stream<Integer> stream1 = stream.filter(new Predicate<Integer>() { //会返回一个筛选过的流,记得接它
/*
a代表流的每个元素
返回值为true,数据就会保留
返回值为false,数据就会被去掉
*/
@Override
public boolean test(Integer a) {
return a % 2 == 0;
}
});
//简化效果
// Stream stream1 = stream.filter(a -> a % 2 == 0);
//遍历
stream1.forEach(integer -> {
System.out.println(integer); //22 ,44
});
filter里面是一个"Predicate函数式接口",每次使用可以先new这个接口出来,再对应使用Lambda简化
Stream<Integer> stream = Stream.of(11, 22, 33, 44, 55, 66);
//截取前3个数据
Stream<Integer> limit = stream.limit(3);
//遍历
limit.forEach(integer -> System.out.println(integer)); //11 22 33
Stream<Integer> stream = Stream.of(11, 22, 33, 44, 55, 66);
//截取前40个数据,如果数量不够,也不会报错
Stream<Integer> limit1 = stream.limit(40);
limit1.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer integer) {
System.out.println(integer); //11 22 33 44 55 66
}
});
Stream<Integer> stream = Stream.of(11, 22, 33, 44, 55, 66);
//跳过前三个数据
Stream<Integer> skip = stream.skip(3);
skip.forEach(integer -> System.out.println(integer)); // 44 55 66
Stream<Integer> stream = Stream.of(11, 22, 33, 44, 55, 66);
// 跳过前20个数据,数量不够也不会报错
Stream<Integer> skip1 = stream.skip(20);
skip1.forEach(integer -> System.out.println(integer)); //什么都没有了,不会报错
//将流中的字符串转为整数类型
Stream<String> stream = Stream.of("11", "22", "33", "44", "55", "66");
/*
String: 流中数据原来的类型
Integer : 要变的类型
*/
Stream<Integer> stream1 = stream.map(new Function<String, Integer>() { //有返回值,记得接
@Override
public Integer apply(String s) {
return Integer.parseInt(s); //这步需要自己操作转换对应的类型
}
});
Stream<String> stream = Stream.of("11", "22", "33", "44", "55", "66");
//把String流变成Integer流,再进行筛选奇数的流出来并遍历
Stream<Integer> stream1 = stream.map(new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return Integer.parseInt(s);
}
});
Stream<Integer> stream2 = stream1.filter(new Predicate<Integer>() {
@Override
public boolean test(Integer integer) {
return integer % 2 != 0;
}
});
stream2.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer integer) {
System.out.println(integer);
}
});
map里面是一个"Function函数式接口",每次使用可以先new这个接口出来,再对应使用Lambda简化
Stream<Integer> stream = Stream.of(11, 22);
Stream<Integer> stream1 = Stream.of(33, 44);
//合并流(前提是两个流的数据类型是一样的)
Stream<Integer> concat = Stream.concat(stream, stream1);
//方法引用简化输出
concat.forEach(System.out::println); //11 22 33 44
文章对你有所帮助的话,欢迎给个赞或者 star,你的支持是对作者最大的鼓励,不足之处可以在评论区多多指正,交流学习