java8 新特性 stream 操作

stream 操作锦集

文章中方法适用于 Java 1.8 及以上版本

排序

//按年龄排序
List<User> collect = list.stream()
    .sorted((e1, e2) -> {
        //先按年龄排序
        return e1.getAge().compareTo(e2.getAge());
    })
    .collect(Collectors.toList());

筛选

List<User> collect = list.stream()
   //选出年龄大于35岁的
   .filter((e) -> e.getAge() > 35)
   //只要前2个
   .limit(2)
   .collect(Collectors.toList());

去重

List<HospitalWardVo> hospitalDepartmentList = hospitalWardVos.stream()
	.collect(Collectors.collectingAndThen(
		 Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(
				HospitalWardVo::getWardAttributesId))), ArrayList::new)
        );

多字段去重

  List<HospitalDepartmentVo> departmentClasss = result.stream().collect(
  		Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(
                   o -> o.getHospitalId() + ";" + o.getStandardDepartmentClassId()
                ))), ArrayList::new));

List 中单独返回某个属性值

List<String> wardIds = userWardDepartments.stream().map(
	UserWardDepartment::getId).collect(Collectors.toList()
);

List 返回新对象

List<Map> childNode = hospitalDepartmentArr.stream().map((hospitalDepartmentObj) -> {
   Map hospitalDepartmentMap = new HashMap<>(16);
    hospitalDepartmentMap.put("id", hospitalDepartmentObj.getId());
    hospitalDepartmentMap.put("showId", hospitalDepartmentObj.getId());
    hospitalDepartmentMap.put("showName", hospitalDepartmentObj.getWardAttributesName());
    hospitalDepartmentMap.put("level", "2");
    hospitalDepartmentMap.put("pid", item.getWardAttributesId() + "_1");
    return hospitalDepartmentMap;
}).collect(Collectors.toList());

你可能感兴趣的:(Tomcat,java,开发语言)