基本数据
ArrayList<Student> lists = new ArrayList<>();
lists.add(new Student("张三", 15, 1541));
lists.add(new Student("李四", 19, 1549));
lists.add(new Student("王五", 55, 1543));
lists.add(new Student("赵六", 8, 1548));
lists.add(new Student("李七", 8, 1549));
lists.add(new Student("王八", 19, 1545));
数据求和
//Student::getAge 表示根据这个属性进行求和
//mapToInt 表示返回值类型为int
int sum = lists.stream().mapToInt(Student::getAge).sum();
最大值
//Student::getAge 表示根据这个属性进行求和
//mapToDouble表示返回值类型为double
//max()返回的是OptionalDouble类型 需要用getAsInt()转换成int类型
double max = lists.stream().mapToDouble(Student::getAge).max().getAsDouble();
最小值
//Student::getAge 表示根据这个属性进行求和
//mapToDouble表示返回值类型为double
//min()返回的是OptionalDouble类型 需要用getAsDouble()转换成double类型
double max = lists.stream().mapToDouble(Student::getAge).min().getAsDouble();
平均值
//Student::getAge 表示根据这个属性进行求和
//mapToDouble表示返回值类型为double
//average()返回的是OptionalDouble类型 需要用getAsDouble()转换成double类型
double average = lists.stream().mapToDouble(Student::getAge).average().getAsDouble();
过滤
//将年龄小于19的收集到一个list集合zho
//filter 过滤函数 s->s.getAge s遍历集合中的对象,将小于19的数据过滤出来
//collect 讲过滤的数据收集成一个List集合也可以收集成Set集合或者Collection集合
List<Student> filter = lists.stream().filter(s -> s.getAge() < 19).collect(Collectors.toList());
排序
//单字段排序 按照年龄降序排序
//用sorted进行排序
//Comparator.comparing(Student::getAge)代表用什么值进行排序比较(默认升序)
//reversed())表示反响排序
//collect(Collectors.toList()) 将其收集成list集合
List<Student> sort = lists.stream().sorted(Comparator.comparing(Student::getAge)
.reversed()).collect(Collectors.toList());
//多字段排序 按照年龄降序排序 年龄相同按照学号学号降序排序
//reversed()为取反排序
//用thenComparing()来添加字段排序
//(o1, o2) -> o2 - o1) 降序
List<Student> sort2 = lists.stream()
.sorted(Comparator.comparing(Student::getAge).reversed()
.thenComparing(Student::getSno,(o1, o2) -> o2 - o1)).collect(Collectors.toList());
注意revered()不能用多次 多次使用会相当于“反反”变为升序
去重
注意: 去重是比较hashCode()和equals()的。要重写改方法
lists.add(new Student("张三", 15, 1541));
lists.add(new Student("李四", 19, 1549));
lists.add(new Student("李四", 19, 1549));
lists.add(new Student("赵六", 8, 1548));
lists.add(new Student("李七", 8, 1549));
lists.add(new Student("王八", 19, 1545));
List<Student> collect = lists.stream().distinct().collect(Collectors.toList());
collect.forEach(s-> System.out.println(s));
分组
ArrayList<Student> lists = new ArrayList<>();
lists.add(new Student("张三", 15, 1541));
lists.add(new Student("李四", 15, 1549));
lists.add(new Student("王五", 55, 1543));
lists.add(new Student("赵六", 55, 1548));
lists.add(new Student("李七", 8, 1549));
lists.add(new Student("王八", 19, 1545));
//分组
Map<Integer, List<Student>> map = lists.stream().collect(Collectors.groupingBy(Student::getAge));
map.forEach((k,v)->{
System.err.println("年龄为"+k+"的组为:");
v.stream().forEach(s-> System.err.println(s));
});
集合转换
List相互转换,List对象转换为List,ViewAffair实体实现构造方法:
public ViewAffair(Affair affair){
this.name = affair.getName();
}
List vos = affairs.stream().map(ViewAffair::new).collect(Collectors.toList());