java流式操作

是对集合对象功能的增强,它专注于对集合对象非常便利、高效的聚合操作,或者大批量数据操作,借助于lambda 表达式,提高
编程效率和可读性。同时提供串行和并行俩种模式进行操作。
在当前大数据爆炸的年代,在数据来源多样化、数据海量化的今天不得不脱离RDBMS,或者以底层返回的数据结构为基础进行上层的数据统计。
而java 的集合API中,仅仅有极少的辅助方法,更多时候需要程序员用Iterator来遍历集合,完成相应的聚合逻辑。这是一种不高效的方法

在java 7 中如果要发现 type 为grocery的所有交易,然后返回降序排列的ID需要这样写

List<Transaction> gTs = new ArrayList<>();
for(Transaction t:transactions){
	if(t.type == grocery){
		gTs.add(t);
	}
}
Collections.sort(gts,new Comparator<Transaction>(){
	@Override
	public int compare(Transaction o1,Transaction o2){
		return o1.getValue() - o2.getValue();
	}
})
List<Integer> l = new ArrayList<>();
for(Transaction t:gTs){
	l.add(t.getId());
}
而是用java8 Stream
transactions.stream().filter(a->a.type == grocery).map(a->a.getId()).sorted().collect(Collectors.toList());
  • 关于lambda表达式
//接口中只有一个抽象方法
//object方法除外
//默认方法除外
 	new Thread(()->System.out.println("xxxx"));
	new Thread(new Runnable(){
		  	@Override
			  public void run (){
		  		System.out.println("xxxx");
			}
		  });

现在我们再看 Stream ,其实我们上面的写法, xxx.stream().filter().map().sorted().collect(); 像是一个管道pipeline一样
将数据源的数据流 过滤排序采集 最后生成结果数据。
注意:在管道中的流的数据永远不会改变 同时不会在内存中存储、也不能够重复使用。我们还要注意 管道中的元素是一个个被处理的 而不是一批批处理。

  • 常见用法
//flatMap flatMap 将 List<Integer>扁平化 转化为 Stream<Integer>
		Stream<List<Integer>> sl = Stream.of(Arrays.asList(1,2),Arrays.asList(3,4));
		Stream<Integer> si = sl.flatMap(childList->childList.stream());

		//过滤整型数组
		Integer[] sixNums = {1, 2, 3, 4, 5, 6};
		Integer[] res = Stream.of(sixNums).filter(a->a%2 == 0).toArray(Integer[]::new);
		//过滤文件 中的line
		File file = new File("C:\\Users\\InAHurry\\Desktop\\a.txt");
		BufferedReader bf =  new BufferedReader(new FileReader(file));
		List<String> s = bf.lines().flatMap(line->Stream.of(line.split(" "))).filter(word->word.length()>0).
				collect(Collectors.toList());
		//利用peek 查看元素
				List<String> ls=Stream.of("you","are")
				.peek(a->System.out.println(a)).map(s->s.toUpperCase())
				.peek(a->System.out.println(a)).collect(Collectors.toList());
		//利用reduce 组合元素(求最大值 最小值 求和 求平均)
				Integer[] sixNums = {1, 2, 3, 4, 5, 6};
		int sum = Stream.of(sixNums).reduce(0,(a,b)->a+b);
		int min = Stream.of(sixNums).reduce(Integer.MAX_VALUE,Integer::min);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值