当前位置: 代码迷 >> 综合 >> 关于java8中的流式计算
  详细解决方案

关于java8中的流式计算

热度:43   发布时间:2024-01-20 17:49:33.0
  • 集合的流式操作
    • 流有串行和并行两种,串行流上的操作是在一个线程中依次完成,而并行流则是在多个线程上同时执行。并行与串行的流可以相互切换:通过 stream.sequential() 返回串行的流,通过 stream.parallel() 返回并行的流。相比较串行的流,并行的流可以很大程度上提高程序的执行效率
    • Stream 和Collection集合的区别:Collection是一种静态的数据结构,而Stream是有关计算的,前者主要面向内存,存储在内存中,后者主要面向CPU,通过CPU计算
    • Java 8 引入了流式操作(Stream),通过该操作可以实现对集合(Collection)的并行处理和函数式操作。根据操作返回的结果不同,流式操作分为中间操作和最终操作两种。最终操作返回一特定类型的结果,而中间操作返回流本身,这样就可以将多个操作依次串联起来。根据流的并发性,流又可以分为串行和并行两种。流式操作实现了集合的过滤、排序、映射等功能。

 

流的出现是为了获得更高的性能,但并不是说使用了流之后性能肯定会得到提升,因此,我们需要谨慎使用。————尴尬,你以为用了流式计算会快很多,然而测试结果并不是……

public class StreamTest {static class User{private int id;String name;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public User(int id, String name) {this.id = id;this.name = name;}}private static List<User> processData() {ArrayList<User> users = new ArrayList<User>();//准备500w数据for(int i=0;i<500000;i++){users.add(new User(i,"张三"+i));users.add(new User(++i,"李四"+i));users.add(new User(++i,"王五"+i));}return users;}public static void main(String[] args) {List<User> users = processData();long start = System.currentTimeMillis();// List<User> c =users.stream().filter(x -> x.getName().startsWith("王")).filter(x->x.getId()>10000).collect(Collectors.toList());ArrayList<User> xx=new ArrayList<>();for (User userT:users){if(userT.getName().startsWith("王")&&userT.getId()>10000){xx.add(userT);}}long cost = System.currentTimeMillis()-start;System.out.println(cost);//System.out.println(xx);}
}

测试结果显示流式计算 60+

for循环 20+

总的来说,流式计算因为引入了lambda,看起来好看了很多,但是实际用来的结果可能和你想的不同!