Java8之Stream

77 阅读1分钟

java8的新特性增加了流的操作,当我们操作流的时候,是不会改变原数组(数据)的。

下面介绍流的一些操作:
1.filter,将流数据过滤,过滤符合条件的数据


List<String> names = Arrays.asList("perter", "anna", "mike");
long a = names.stream().filter(item -> item.startsWith("a")).count();
System.out.println(a);
//expectd output: 1

2.map,对流数据操作,返回操作后的数据

List<String> collect2 = names.stream().
    map(item -> item + "a").collect(Collectors.toList());   
System.out.println(collect2);
System.out.println(names);
//expected output: [pertera, mikea, annaa]

3.match,查找符合条件的流数据,如果符合条件,那么返回true,否则饭hifalse

//任一符合
boolean a1 = names.stream().anyMatch(item -> item.startsWith("a"));
System.out.println(a1);
//expected output: true

//所有符合
boolean a2 = names.stream().allMatch(item -> item.startsWith("a"));
System.out.println(a2);
//expected output:false

4.sorted,将流数据进行排序,如果不写的话默认为自然排序

List<String> collect = names.stream().sorted().collect(Collectors.toList());
System.out.println(collect);
//expected output:[anna, mike, perter]


List<String> collect3 = names.stream().sorted((b, c) -> c.compareTo(b)).collect(Collectors.toList());
System.out.println(collect3);
//expected output:[perter, mike, anna]

上面就是对流的一些基本操作,上面的流是线性的,单线程,我们可以使用并发线程的流, parallelStream(),显示,它的速度确实比简单的stream()要快上许多,下面进行百万级别数据的测试:


int max = 1000000;
ArrayList<String> list = new ArrayList<>(max);
for(int i=0;i<max;i++){
    UUID uuid = UUID.randomUUID();
    list.add(uuid.toString());
}

//纳秒级别 stream测试
long nanoTime = System.nanoTime();
long count = list.stream().sorted().count();
long nanoTime1 = System.nanoTime();
long millis = TimeUnit.NANOSECONDS.toMillis(nanoTime1 - nanoTime);
System.out.println(millis);
//expected output:548
//纳秒级别 parallelStream测试
long nanoTime = System.nanoTime();
long count = list.parallelStream().sorted().count();
long nanoTime1 = System.nanoTime();
long millis = TimeUnit.NANOSECONDS.toMillis(nanoTime1 - nanoTime);
System.out.println(millis);
//expected output:368

从上面的测试可以看出,百万级别数据排序并发的stream确实比单纯的stream快