关注:Java提升营,最新文章第一时间送达,10T 免费学习资料随时领取!!!
Stream(流)是一个来自数据源的元素队列并支持聚合操作
Stream API可以极大提高Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。
这种风格将要处理的元素集合看作一种流,流在管道中传输,并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。
以上的流程转换成Java代码为:
List<Integer> transactionsIds = widgets.stream() .filter(b -> b.getColor() == RED) .sorted((x,y) -> x.getWeight() - y.getWeight()) .mapToInt(Widget::getWeight) .sum(); 复制代码
在java 8中, 集合接口有两个方法来生成流:
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList()); 复制代码
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); // 获取空字符串的数量 int count = strings.parallelStream().filter(string -> string.isEmpty()).count(); 复制代码
List number = Arrays.asList(2,3,4,5); List square = number.stream().map(x->x*x).collect(Collectors.toList()); 复制代码
List names = Arrays.asList("Reflection","Collection","Stream"); List result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList()); 复制代码
List names = Arrays.asList("Reflection","Collection","Stream"); List result = names.stream().sorted().collect(Collectors.toList()); 复制代码
Random random = new Random(); random.ints().limit(10).forEach(System.out::println); 复制代码
List number = Arrays.asList(2,3,4,5,3); Set square = number.stream().map(x->x*x).collect(Collectors.toSet()); 复制代码
Random random = new Random(); random.ints().limit(10).forEach(System.out::println); 复制代码
//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.*; class Demo { public static void main(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); } } 复制代码
输出:
[4, 9, 16, 25] [Stream] [Collection, Reflection, Stream] [16, 4, 9, 25] 4 9 16 25 6 复制代码