1、将集合转换为计算流,对集合进行排序,分页,合并,计算,过滤等操作。
创建实体类
import lombok.Data;
import lombok.experimental.Accessors;
@Data //此注解可以免写get,set方法
@Accessors(chain = true) //此注解可以写了链式变成new Student().setAge(10).setName("张三"):
public class Student {
private String name;
private Integer age;
private String sex;
}
使用计算流操作集
public static void main(String[] args) { Student student = new Student().setName("张三").setAge(18).setSex("男"); Student student2 = new Student().setName("张三").setAge(18).setSex("男"); Student student3 = new Student().setName("李四").setAge(23).setSex("女"); List<Student> list = new ArrayList<>(); list.add(student); list.add(student2); list.add(student3); //count()集合长度 //forEach循环集合里面的对象并输出,e代表集合里面的每个对象 list.stream().forEach(e -> { System.out.println("****forEach list:" + e); }); //distinct是对集合里面的对象进行去重 list.stream().distinct().forEach(e -> { System.out.println("****distinct list:" + e); }); //collect(Collectors.toList())将返回的流转换为list<Student>对象来接收 List<Student> listStream = list.stream().collect(Collectors.toList()); //将数据转换为map,Function.identity()得到整个对象,(key1,key2)->key2是定义的覆盖规则
Map<String, Map> levelMap = levelList.stream().collect( Collectors.toMap(level -> MapUtils.getString(level, "service_name"), Function.identity(), (key1, key2) -> key2));//默认是按照年龄升序,降序,需要使用reversse list.stream().sorted(Comparator.comparing((Student s) ->{ return s.getAge(); })); //倒序 list.stream().sorted(Comparator.comparing((Student s) ->{ return s.getAge(); }).reversed()); //分页,skip下标(page-1)*limit,limit限制条数 list.stream().skip(0).limit(10); //过滤年龄大于18岁的学生集合 list.stream().filter((s)->{ return s.getAge()>18; }).collect(Collectors.toList()); //合并两个集合并去重 //第一种方法: List<Student> concatList = new ArrayList<>(); concatList.add(new Student().setSex("女").setName("王子").setAge(24)); List<Student> unionResult = Stream.of(list, concatList).flatMap(Collection::stream).distinct().collect(Collectors.toList()); unionResult.forEach(s->{ System.out.println("list合并:"+s); }); //第二种方法: Stream.of(list, concatList) .flatMap(Collection::stream).forEach(System.out::println); //更换泛型为其他实体类或者map类型 list.stream().map(e->{ Persion p = new Persion(); BeanUtils.copyProperties(e,p); return p; }).collect(Collectors.toList()).forEach(p->{ System.out.println("$$$$copyList:"+p); }); }
日志结果:
****forEach list:Student(name=张三, age=18, sex=男)
****forEach list:Student(name=张三, age=18, sex=男)
****forEach list:Student(name=李四, age=23, sex=女)
****distinct list:Student(name=张三, age=18, sex=男)
****distinct list:Student(name=李四, age=23, sex=女)
list合并:Student(name=张三, age=18, sex=男)
list合并:Student(name=李四, age=23, sex=女)
list合并:Student(name=王子, age=24, sex=女)
Process finished with exit code 0