java8常见lambda函数简略笔记
stream函数简要描述:
这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。
元素流在管道中经过中间操作的处理,最后由最终操作得到前面处理的结果。
为函数式编程而生。对stream的任何修改都不会修改背后的数据源。
stream()方法的使用示例:
map()对列表遍历进行操作
filter()过滤操作
sorted(a,b) a减b从小到大,b减a从大到小
@Test
public void test() {
List<String> listStr = Arrays.asList("赵", "钱", "1", "123", "12");
List<Object> firstNames = listStr.stream().map(String::toUpperCase).filter((str) -> {
return !str.equals("赵");
}).sorted((a, b) -> {
return b.compareTo(a); //b-a
}).collect(Collectors.toList());
firstNames.forEach(p -> {
System.out.print(p + " ");
});
}
输出结果:
三级嵌套标题代码
/**
* 获取树形结构标题内容
* @return
*/
@Override
public List<CategoryEntity> listWithTree() {
List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
List<CategoryEntity> categoryEntityList = categoryEntities.stream().filter((categoryEntity -> {
//通过filter过滤,只留下一级标题
return categoryEntity.getParentCid() == 0;
})).map((categoryEntity)->{
//map遍历为每个子元素列表赋值(须在entity中添加categoryChildrens属性 打上@TableField(exist=false)注解 )
categoryEntity.setCategoryChildrens(getChildrens(categoryEntity,categoryEntities));
return categoryEntity;
}).sorted((categoryEntity1, categoryEntity2) -> {
//根据entity的.getSort()属性值排序 三目运算符防止空指针
return (categoryEntity1.getSort() == null ? 0 : categoryEntity1.getSort()) - (categoryEntity2.getSort() == null ? 0 : categoryEntity2.getSort());
}).collect(Collectors.toList());
return categoryEntityList;
}
/**
* 获取子类别列表,代码和listWithTree差不多参考注释
* @param father
* @param all
* @return
*/
private List<CategoryEntity> getChildrens(CategoryEntity father, List<CategoryEntity> all) {
List<CategoryEntity> categoryEntityList = all.stream().filter((categoryEntity) -> {
return categoryEntity.getParentCid() == father.getCatId();
}).map(categoryEntity -> {
categoryEntity.setCategoryChildrens(getChildrens(categoryEntity, all));
return categoryEntity;
}).sorted((categoryEntity1, categoryEntity2) -> {
return (categoryEntity1.getSort() == null ? 0 : categoryEntity1.getSort()) - (categoryEntity2.getSort() == null ? 0 : categoryEntity2.getSort());
}).collect(Collectors.toList());
return categoryEntityList;
}