1.forEach遍历
forEach:该方法接收一个Consumer接口函数,将每一个流元素交给该函数处理
forEach方法:用来遍历流中的数据
注:是一个终结方法,遍历之后就不能继续调用Stream流中的其他方法
public class Stream_ForEach {
public static void main(String[] args) {
//获取一个Stream流
Stream<String>stream= Stream.of("张三","李四","王五","赵六");
//使用Stream流的方法forEach对stream流中的数据遍历
stream.forEach((String name)->{
System.out.println(name);
});
}
}
2. filter过滤
filter:用于对Stream流中的数据进行过滤
filter(Predicate<? super T>predicate)
filter方法的参数Predicate是一个函数式接口,可以使用lambda表达式
public class Stream_filter {
public static void main(String[] args) {
//创建一个Stream流
Stream<String> stream = Stream.of("张三", "李四", "王五", "赵六1", "刘老七");
//单条件过滤
Stream<String> stream1 = stream.filter((String name) -> {
return name.startsWith("刘");
});
//多条件过滤
List<String> stream2 = stream.filter((String name) -> {
if(name.length()>=3 && name.equals("刘老七")){
return true;
}
return false;
}).collect(Collectors.toList);
//遍历stream1
stream1.forEach((name)-> System.out.println(name));
//输出stream2
System.out.println(stream2)
}
}
3. distinct去重
public class Stream_distinct {
public static void main(String[] args) {
//创建一个Stream流
Stream<String> stream = Stream.of("张三", "张三","张三","李四", "王五", "赵六1", "刘老七");
//去重
List<String> stream1 = stream().distinct().collect(Collectors.toList());
//输出stream1
System.out.println(stream1)
}
4. limit截取
limit:用于截取流中的元素
limit可以对流进行截取,只取用前n个
limit(long maxSize);
参数是一个long型,如果集合当前长度大于参数则进行截取,否则不进行操作
limit是一个延迟方法,可以继续使用Stream流方法
public class Stream_limit {
public static void main(String[] args) {
//创建一个Stream流
Stream<String> stream = Stream.of("张三", "张三","张三","李四", "王五", "赵六1", "刘老七");
//去重
List<String> list = stream().distinct().collect(Collectors.toList());
//截取去重后的前2个元素
list = list.stream().limit(2).collect(Collectors.toList();
//输出stream1
System.out.println(list)
}
}
5. skip跳过
skip方法:用于跳过元素
skip(long n)
如果流的当前长度大于n,则跳过前n个,否则将会得到一个长度为0的空流
public class Stream_skip {
public static void main(String[] args) {
//创建一个Stream流
Stream<String> stream = Stream.of("张三", "张三","张三","李四", "王五", "赵六1", "刘老七");
//去重
List<String> list = stream().distinct().collect(Collectors.toList());
//跳过去重后的前2个元素
list = list.stream().skip(2).collect(Collectors.toList());
//输出stream1
System.out.println(list)
}
}