将List集合存入流中
List<String> list = new ArrayList<>();list.add("张一");list.add("张二");list.add("张三");list.add("李四");list.add("赵五");list.add("张六");list.add("王八");Stream<String> stream = list.stream();
Stream.of 将流中添加参数
Stream<String> stream = Stream.of("张一", "张二");
stream.count(); 统计数量
stream.filter();过滤将流中的参数按条件返回
public static void main(String[] args) {List<String> list = new ArrayList<>();list.add("张一");list.add("张二");list.add("张三");list.add("李四");list.add("赵五");list.add("张六");Stream<String> stream = list.stream();stream.filter((String name)->{ return name.startsWith("张");});}
这里将名字做了判断,String name开头为“张”的参数,将会返回回去。
stream().forEach();将流中参数遍历
public static void main(String[] args) {List<String> list = new ArrayList<>();list.add("张一");list.add("张二");list.add("张三");list.add("李四");list.add("赵五");list.add("张六");list.stream().forEach((String name)->{System.out.println("流中的元素" + name);});}
forEach中的(String name)写什么都可以,主要是要和上面的list中类型一致,将流中的值赋值在String类型的name上,然后输出
实战:将以下两个list的for循环通过流优化
/*** 获取所有的区域和下级经纬度** @return*/@Overridepublic List<RegionInfo> findAllRegionInfo() {List<RegionInfo> regionInfoList = this.mapper.findList();List<Trajectory> listByRegionInfoList = trajectoryService.findListByRegionInfoList(regionInfoList);for (RegionInfo regionInfo : regionInfoList) {List<Trajectory> trajectories = new ArrayList<>();for (Trajectory trajectory : listByRegionInfoList) {if (trajectory.getFenceId().equals(regionInfo.getId())) {trajectories.add(trajectory);}regionInfo.setTrajectoryList(trajectories);}}return regionInfoList;}