List number = Arrays.asList(2,3,4,5); List square = number.stream().map(x->x*x).collect(Collectors.toList());
filter: filter 方法用于通过设置的条件过滤出元素
1 2
List names = Arrays.asList("Reflection","Collection","Stream"); List result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());
sorted: sorted 方法用于对流进行排序
1 2
List names = Arrays.asList("Reflection","Collection","Stream"); List result = names.stream().sorted().collect(Collectors.toList());
limit:limit 方法用于获取指定数量的流
1 2
Random random = new Random(); random.ints().limit(10).forEach(System.out::println);
最终操作(terminal operation)
collect: collect方法用于返回执行中间操作后的结果
1 2
List number = Arrays.asList(2,3,4,5,3); Set square = number.stream().map(x->x*x).collect(Collectors.toSet());
forEach:forEach 方法用来迭代流中的每个数据
1 2
Random random = new Random(); random.ints().limit(10).forEach(System.out::println);
reduce: reduce方法用于将流的元素计算后输出一个值
1 2 3 4
//reduce方法将BinaryOperator用作参数 //在这里,ans变量初始值为0 List number = Arrays.asList(2,3,4,5); int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);
//a simple program to demonstrate the use of stream in java import java.util.*; import java.util.stream.*; classDemo { publicstaticvoidmain(String args[]){ // create a list of integers List<Integer> number = Arrays.asList(2,3,4,5); // demonstration of map method List<Integer> square = number.stream().map(x -> x*x).collect(Collectors.toList());
System.out.println(square); // create a list of String List<String> names = Arrays.asList("Reflection","Collection","Stream"); // demonstration of filter method List<String> result = names.stream().filter(s->s.startsWith("S")). collect(Collectors.toList()); System.out.println(result); // demonstration of sorted method List<String> show = names.stream().sorted().collect(Collectors.toList());
System.out.println(show); // create a list of integers List<Integer> numbers = Arrays.asList(2,3,4,5,2); // collect method returns a set Set<Integer> squareSet = numbers.stream().map(x->x*x).collect(Collectors.toSet());
System.out.println(squareSet); // demonstration of forEach method number.stream().map(x->x*x).forEach(y->System.out.println(y)); // demonstration of reduce method int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i); System.out.println(even); } }