java 8中stream.filter()的用法

实际开发中,我么可能需要在一个list中拿到某个值是某个固定值的list。

 public static void main(String[] args) {
 //new一个list,给list添加三组值。
		List list = new ArrayList<>();
		VehicleInfo vehicleInfo = new VehicleInfo();
		vehicleInfo.setSysOrgId(100);
		vehicleInfo.setTerminalType("2");
		list.add(vehicleInfo);
		VehicleInfo vehicleInfo1 = new VehicleInfo();
		vehicleInfo1.setSysOrgId(100);
		vehicleInfo1.setTerminalType("3");
		list.add(vehicleInfo);
		VehicleInfo vehicleInfo2 = new VehicleInfo();
		vehicleInfo2.setSysOrgId(101);
		vehicleInfo2.setTerminalType("2");
		list.add(vehicleInfo2);
		//查询出sysOrgId是100的集合。
		List vehicleInfos = list.stream().filter(a ->100==a.getSysOrgId()).collect(Collectors.toList());
		//查询出sysOrgId是100的集合的第一个,返回值是Optional类型
		Optional vehicleInfo3 = list.stream().filter(a ->100==a.getSysOrgId()).findFirst();
		//判断vehicleInfo3是不是空的
		if (vehicleInfo3.isPresent()) {
		//把optional的值给实体类
			VehicleInfo vehicleInfo4 = vehicleInfo3.get();
			System.out.println(vehicleInfo4); 
		}
		System.out.println(vehicleInfos);
	}

你可能感兴趣的:(Java基础)