自学的Stream,主要就是几个API,在这里记录下载,以免遗忘
首先就是将集合转换成Stream流,当时举例:
ArrayList<String> list = new ArrayList<String>();
Stream<String> s1 = list.stream();
Object[] array = list.toArray();
Stream<Object> s2 = Arrays.stream(array);
Stream<String> s3 = Stream.of("a","aa");
还有一种是迭代生成:
Stream<Integer> s4 = Stream.iterate(0, (x) -> x+2);
s4.filter((e) -> e<10).filter((a) -> a>0).forEach(System.out::println);
这里做的时输出大于0小于10的循环输出
Stream的filter方法:
是指接受一个lambda表达式,从stream中选择出符合条件的元素
List<Employee> employees = Arrays.asList(
new Employee("1",1 ,1 ),
new Employee("2",2 ,2 ),
new Employee("3",3 ,3 ),
new Employee("4",4 ,4 ),
new Employee("5",5 ,5 )
);
Stream<Employee> s = employees.stream();
s.filter((e) -> e.getAge()>2).filter((a) -> a.getMoney()<= 4).forEach(System.out::println);
备注:括号内的条件是结果需要满足的条件
Stream的map方法:
是指接受一个函数(funtion),这个函数会被应用到每个元素上,从而应映射成一个新元素
flatMap方法与map方法了类似,但是当出现集合嵌套集合的情况时,map方法的结果遍历是会出现嵌套遍历,为了免除麻烦,使用flatMap方法,只会饭会议和集合类似(addAll)方法
Stream的排序sorted:
employees.stream()
.sorted((a,b) -> {
if(a.getAge().equals(b.getAge())) {
return a.getName().compareTo(b.getName());
}else {
return a.getAge().compareTo(b.getAge());
}
}).forEach(System.out::println);
按照年龄排序,年龄相同按照姓名排序
Stream的匹配查找:
Stream<Employee> s = employees.stream();
boolean b = s.allMatch((e) -> e.getName().equals("1"));
System.out.println(b);
代码,查询集合中的元素属性是否全都匹配---allMatch
是否至少匹配一个元素---anyMatch
是不是没有匹配所有元素---noneMatch 双重否定
返回第一个元素--findFirst
元素的个数---count
最大数----max
最小数---min
Stream的归约
reduce -- 可以将流中元素反复结合起来,得到一个值
Stream<Employee> s = list.stream();
Optional<Integer> reduce = s.map(Employee::getAge).reduce(Integer::sum);
Stream的收集器
collect -- 将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
List<String> collect = list.stream().map(Employee::getName)
.collect(Collectors.toList());
将集合元素的名字取出来单独存入一个新的集合
如果需要存放到特殊的数据结构的集合中
HashSet<String> set = list.stream()
.map(Employee::getName)
.collect(Collectors.toCollection(HashSet::new));
收集年龄之和:
Integer integer = list.stream()
.collect(Collectors.summingInt(Employee::getMoney));
其余方法基本重复,就此略过
推荐函数算法:
DoubleSummaryStatistics dss = list.stream()
.collect(Collectors.summarizingDouble(Employee::getMoney));
得到集合的money
完美~~