一、前言
Java 8 型特性-Stream。Stream是对集合(Collection)对象功能的增强,它专注于对集合对象进行聚合操作或者大批量数据操作。Stream API借助于同时出现的Lambda表达式,极大地提高编程效率和程序可读性。同时它提供串行和并行两种模式进行聚合操作,并行模式能够充分利用多核处理器的优势,使用Java7开始提供的fork/join并行执行框架来拆分和加速处理过程。
文章参考:
Stream的介绍和基本使用
菜鸟教程
二、使用
1.流的对象
(1)集合
(2)数组
(3)I/O channel, 产生器generator
2.具体操作
测试数据
static List<User> list = new ArrayList<>();
static List<User> list2 = new ArrayList<>();
static {
for(int i =0;i<10;i++){
Random random = new Random();
User user = new User("name"+random.nextInt(10), random.nextInt(200));
list.add(user);
list2.add(user);
}
}
(1)sort 排序
在排序方面,时间效率和工具类Collections的sort一致,代码量也差不多。但使用Stream还需要使用一个collectior进行收集,开辟一个新的对象,因此略显不足。
long start1 = System.currentTimeMillis();
List<User> list1 = list.stream().sorted((user1,user2)->{
return user1.getAge()-user2.getAge();
}).collect(Collectors.toList());
long end1 = System.currentTimeMillis();
System.out.println("排序时间:"+(end1-start1)+";结果");
list1.stream().forEach(System.out::println);
Collections.sort(list2,(user1,user2)->{
return user1.getAge()-user2.getAge();
});
System.out.println("排序时间:"+(end1-start1)+";结果");
list2.stream().forEach(System.out::println);
(2)过滤(filter),进行筛选
在过滤方面,使用传统结合lamba的写法和Stream比起来也不会麻烦多少。但是再来下面结合映射、规约、统计这些呢。
List<User> list1 = list.stream().sorted((user1,user2)->{
return user1.getAge()-user2.getAge();
}).filter(user -> {return user.getAge()>60;}).collect(Collectors.toList());
// 筛选年龄大于一百的
long end1 = System.currentTimeMillis();
System.out.println("排序筛选时间:"+(end1-start1)+";结果");
list1.stream().forEach(System.out::println);
Collections.sort(list2,(user1,user2)->{
return user1.getAge()-user2.getAge();
});
// 在进行遍历时,删除是不可取的会冲突,但可以进行修改 。.ConcurrentModificationException
// 因此只能考虑再设定一个集合进行存放符合要求的数据
// list2.forEach(
// (user)->{if(user.getAge()>60)
// {
// list2.remove(user);
// } } );
List<User> tempList = new ArrayList<>();
list2.forEach((user)->{
if(user.getAge()>60)
{
tempList.add(user);
System.out.println("test:"+user);
}
});
tempList.stream().forEach(System.out::println);
(3)map 映射(对应修改数据)
映射每个用户对应年龄加一
list.stream().map(user -> {user.setAge(user.getAge()+1);
return user;
}
).forEach(System.out::println);
(4)规约 、匹配查询
/**
* 归约
* reduce(T iden, BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回 T
* reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回 Optional<T>
*/
(5)统计,count,(Integer等基本类型 可以使用 IntSummaryStatic…,可统计ave,max,min,sum)
long num = list.stream().count();
Optional<User> max =list.stream().max((user1, user2)-> {
return user1.getAge()-user2.getAge();
});
System.out.println(num+";"+max);
(6)收集 collector
三、总结
使用Stream,综合进行filter,sort,map,count,等系列操作还是比传统写法还是方便简洁多了,而且时间效率也很高!