1映射操作
属于中间操作
1.1map映射操作
接收一个函数作为参数,这个函数会被应用到每个元素上,并将其映射成一个新的元素,用于转换其他形式或提取信息
案例1:将集合中所有浮点数做四舍五入保留两位小数处理
案例2: 属性的提取
public class TestMap {
public static void main(String[] args) {
List<Double> list= Arrays.asList(3.1415,4.556,5.432,6.738);
list.stream().map(TestMap::k2).forEach(System.out::println);
getName();
addBlood();
}
public static double k2(double x){
return (int)((x*100)+0.5)/100d;
}
public static void getName(){
List<Hero> list= Arrays.asList(new Hero("亚瑟",10000),
new Hero("项羽",14000),
new Hero("小乔",5000));
list.stream().map(Hero::getName).forEach(System.out::println);
}
public static void addBlood(){
List<Hero> list= Arrays.asList(new Hero("亚瑟",10000),
new Hero("项羽",14000),
new Hero("小乔",5000));
//不改变原有数据
list.stream().map(h->{
Hero hero=new Hero(h.getName(),h.getBlood());
hero.setBlood(hero.getBlood()+1000);
return hero;
}).forEach(System.out::println);
//改变原有数据
// list.stream().map(h->{
// h.setBlood(h.getBlood()+1000);
// return h;
// }).forEach(System.out::println);
}
}
1.2flatMap操作
接收一个函数作为参数,将流中的每个值都换成另一个流,把所有流连接成一个流
案例:将两个字符集合合并成一个新的字符集合
public class TestFlatMap {
public static void main(String[] args) {
String str="a,b,c,d,e";
String str1="m,m,j";
List<String> list=Arrays.asList(str,str1);
Stream<String> stringStream = list.stream().flatMap(TestFlatMap::f);
stringStream.forEach(System.out::println);
// Stream<Stream<String>> streamStream = list.stream().map(TestFlatMap::f);
// streamStream.forEach(s->{
// s.forEach(System.out::println);
// });
}
public static Stream<String> f(String str){//使用逗号分隔的字符串
String[] strs=str.split(",");
Stream<String> stream = Arrays.stream(strs);
return stream;
}
}
1.3mapToInt mapToLong mapToDouble
以一个映射函数为参数,将流中的每一个元素处理后生成一个新流
用于最大最小值,平均值,求和等操作
public class TestMapToInt {
public static void main(String[] args) {
testToInt();
summary();
}
public static void range(){
//闭区间
System.out.println(IntStream.rangeClosed(1, 100).sum());;
// int sum = IntStream.rangeClosed(1, 100).sum();
// System.out.println(sum);这种情况不包含100
Stream<Integer> boxed = IntStream.rangeClosed(1, 10).boxed();//转换为对象流
}
public static void summary() {
IntSummaryStatistics intSummaryStatistics = Stream.of("1", "2", "3").
mapToInt(Integer::valueOf).summaryStatistics();
System.out.println(intSummaryStatistics.getMax());
System.out.println(intSummaryStatistics.getMin());
System.out.println(intSummaryStatistics.getSum());
}
public static void maxAndMin() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
OptionalInt max = list.stream().mapToInt(Number::intValue).max();
OptionalInt min = list.stream().mapToInt(Number::intValue).min();
System.out.println(max.getAsInt());
System.out.println(min.getAsInt());
}
public static void testToInt() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
list.stream().mapToInt(x -> x * 10).forEach(System.out::println);
}
}
2 归约reduce
也称作缩减操作,是把一个流缩减成一个值,实现的对集合求和,求乘积,求最大值,最小值操作
public class TestReduce {
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
//使用mapToInt转成数据的操作
// int sum = stream.mapToInt(Number::intValue).sum();
// System.out.println(sum);
//使用归约方法1
Optional<Integer> reduce = stream.reduce(Integer::sum);
System.out.println(reduce.get());
//使用归约方法2
int sum = stream.reduce(0, Integer::sum);
System.out.println(sum);
}
}
public class TestReduceRef {
public static void main(String[] args) {
//求所有英雄血量总和
//求所有英雄血量最多的英雄
List<Hero> heroList= Arrays.asList(new Hero("亚瑟",10000),
new Hero("项羽",14000),
new Hero("小乔",5000));
//求和
heroList.stream().reduce(0,(sum,hero)->sum+=hero.getBlood(),(Integer::sum));
Optional<Integer> reduce = heroList.stream().map(Hero::getBlood).reduce(Integer::sum);
System.out.println(reduce.get());
//求最高值
Integer reduce1 = heroList.stream().map(Hero::getBlood).reduce(0, Integer::max);
System.out.println(reduce1);
}
}
3 排序
属于中间操作
sorted():自然排序,要求流中元素实现Compable接口
sorted(Comparable comparator)自定义排序
自定义排序处理
public class TestSorted {
public static void main(String[] args) {
List<Staff> list= Arrays.asList(new Staff("张三", 18,10000),
new Staff("李四", 19,7000),
new Staff("王五", 20,5000)
);
list.stream().sorted().forEach(System.out::println);
}
}
排序器
public class TestSortedComparator {
public static void main(String[] args) {
List<Emp> list= Arrays.asList
(new Emp("张三", 18,10000),
new Emp("李四", 19,7000),
new Emp("王五", 20,5000)
);
//按年龄排序
list.stream().sorted(Comparator.comparingInt(Emp::getAge))
.forEach(System.out::println);
//按工资降序排序,即添加reversed(),如果没有,就是按工资升序排列
list.stream().sorted(Comparator.comparingInt(Emp::getSalary).reversed())
.forEach(System.out::println);
//按年龄升序排列,如果年龄相同,则按工资升序排列
list.stream().sorted(Comparator.comparingInt(Emp::getAge)
.thenComparingInt(Emp::getSalary));
}
}
4 收集collect
属于终端操作
把一个流收集起来,最终可以是收集成一个值,也可以收集成一个新的集合
因为流不存储数据,如果流操作完成后,还想继续使用这些经过处理的数据,需要放到一个新的集合中,toList,toSet,toMap,toCollection法等相关操作
4.1 生成1个新的集合
转list集合
List<Emp> list= Arrays.asList(new Emp("张三",18,10000),
new Emp("李四",20,20000),
new Emp("李五",22,15000),
new Emp("赵六",54,30000));
List<Emp> newList = list.stream()
.filter(x -> x.getName().startsWith("李"))
.collect(Collectors.toList());
newList.forEach(System.out::println);
转set
public static void toSet(){
Set<Integer> collect = Stream.of(1, 2, 3,4, 5, 6)
.filter(x -> x % 2 == 0)
.collect(Collectors.toSet());
collect.forEach(System.out::println);
}
转Map操作
public static void toMap(){
List<Emp> list= Arrays.asList(new Emp("张三",18,10000),
new Emp("李四",20,20000),
new Emp("李五",22,15000),
new Emp("赵六",54,30000));
list.stream().filter(e->e.getSalary()>=20000).collect(Collectors.toMap(Emp::getName, Emp::getSalary));
}
转Collection类
public static void toCollection(){
ArrayList<String> collect=Stream.of("abc","ddd","xx")
.collect(Collectors.toCollection(ArrayList::new));
collect.forEach(System.out::println);
}
4.2统计和计算
counting:统计数量可以用count替换
Long x = list.stream().filter(e -> e.getName().startsWith("李"))
.collect(Collectors.counting());
//可以替换
long y = list.stream().filter(e -> e.getName().startsWith("李")).count();
获取最高值:maxBy
//获取最高值
Optional<Emp> collect = list.stream().filter(e -> e.getSalary() > 20000)
.collect(Collectors.maxBy(Comparator.comparingInt(Emp::getSalary)));
System.out.println(collect.get());
//可以替换
Optional<Emp> collect1 = list.stream().filter(e -> e.getSalary() > 20000)
.max(Comparator.comparingInt(Emp::getSalary));
获取最低值:minBy
求和
summingInt
//求和
Integer collect = list.stream().collect(Collectors.summingInt(Emp::getSalary));
System.out.println(collect);
//可以替换
list.stream().mapToInt(Emp::getSalary).sum();
求平均
averagingDouble
list.stream().collect(Collectors.averagingDouble(Emp::getSalary));
//可以替换
list.stream().mapToInt(Emp::getSalary).average().getAsDouble();
所有操作
summarizingInt
IntSummaryStatistics collect = list.stream()
.collect((Collectors.summarizingInt(Emp::getAge)));
System.out.println(collect.getMax());
System.out.println(collect.getMin());
System.out.println(collect.getAverage());
System.out.println(collect.getSum());
4.3 分组
分区:partitioningBy,只能分成两组,符合条件的是两组,不符合条件的是另一组
public class TeatPartitioningBy {
public static void main(String[] args) {
List<Emp> list= Arrays.asList(new Emp("张三",18,10000),
new Emp("李四",20,20000),
new Emp("李五",22,15000),
new Emp("赵六",54,30000));
Map<Boolean, List<Emp>> collect = list.stream().collect(Collectors.partitioningBy(e -> e.getSalary() > 20000));
collect.forEach((k,v)-> System.out.println(k+"\t"+v));
}
}
分组:groupingBy
将集合分成多个Map,如以员工年龄分组,工资分组
public class TestGroupingBy {
public static void main(String[] args) {
List<Employer> list= Arrays.asList(new Employer("张三",23,"研发部","男"),
new Employer("李四",20,"销售部","男"),
new Employer("李五",30,"销售部","女"),
new Employer("李四",21,"销售部","女"));
//按部门分组
Map<String, List<Employer>> collect = list.stream()
.collect(Collectors.groupingBy(Employer::getDept));
collect.forEach((k,v)-> {
System.out.println("部门名称:"+k);
v.forEach(System.out::println);//部门里的员工循环
});
//按性别分组
Map<String, List<Employer>> collect1 = list.stream()
.collect(Collectors.groupingBy(Employer::getGender));
collect1.forEach((k,v)->{
if("男".equals(k)) {
System.out.println("性别:" + k);
v.forEach(System.out::println);
}//性别里的员工循环
});
//先按性别,再按部门
Map<String, Map<String, List<Employer>>> collect2 = list.stream().collect(Collectors.groupingBy(Employer::getGender,
Collectors.groupingBy(Employer::getDept)));
collect2.forEach((k,v)->{
System.out.println("性别:" + k);
v.forEach((k1,v1)->{
System.out.println("部门名称:"+k1);
v1.forEach(System.out::println);//部门里的员工循环
});
});
}
}
4.4 拼接操作joining
//joining 无参 直接拼接
String str=list.stream().map(Employer::getName)
.collect(Collectors.joining());
System.out.println(str);
//一个参数,连接符号
String collect = list.stream().map(Employer::getName).collect(Collectors.joining("_"));
System.out.println(collect);;
//三个参数,连接符号,前缀,后缀
String collect1 = list.stream().map(Employer::getName).collect(Collectors.joining("_","[","]"));
System.out.println(collect1);