Java 8 are out for so long, Stream API to understand the next?

SpringBoot actual electricity supplier item mall (20k + star) Address: github.com/macrozheng/...

Summary

Java 8 introduces a new Stream API, you can use the statement of approach to handling data, which greatly facilitates the collection of operations, so that we can use less code to implement more complex logic, this paper to be some common Stream API introduction.

What is Stream?

Stream (flow) from a queue element is a data source that supports polymerization operation.

  • Source: data sources, data source configured Stream object stream, such as an object constructed by a Stream List, the Source List is the data;
  • Polymerization operation: After Stream Object Stream object returns processing such that the specified operation is called rule data aggregation operations, such as filter, map, limit, sorted are all polymerization operation.

Stream polymerization operation

Background

UmsPermission objects mall will herein as an example to introduce the common operations Stream API. UmsPermission is a permission object is divided into three permission, catalogs, menus, and buttons, objects are defined as follows.

public class UmsPermission implements Serializable {
    private Long id;

    @ApiModelProperty(value = "父级权限id")
    private Long pid;

    @ApiModelProperty(value = "名称")
    private String name;

    @ApiModelProperty(value = "权限值")
    private String value;

    @ApiModelProperty(value = "图标")
    private String icon;

    @ApiModelProperty(value = "权限类型:0->目录;1->菜单;2->按钮(接口绑定权限)")
    private Integer type;

    @ApiModelProperty(value = "前端资源路径")
    private String uri;

    @ApiModelProperty(value = "启用状态;0->禁用;1->启用")
    private Integer status;

    @ApiModelProperty(value = "创建时间")
    private Date createTime;

    @ApiModelProperty(value = "排序")
    private Integer sort;

    private static final long serialVersionUID = 1L;
    
    //省略所有getter及setter方法
}
复制代码

Create a Stream object

Stream object is divided into two stream objects a serial and a parallel stream object.

// permissionList指所有权限列表
// 为集合创建串行流对象
Stream<UmsPermission> stream = permissionList.stream();
// 为集合创建并行流对象
tream<UmsPermission> parallelStream = permissionList.parallelStream();
复制代码

filter

Stream of elements in the filtering operation, returns the corresponding element when the setting condition returns true.

// 获取权限类型为目录的权限
List<UmsPermission> dirList = permissionList.stream()
    .filter(permission -> permission.getType() == 0)
    .collect(Collectors.toList());
复制代码

map

After acquiring the elements Stream conversion process. Such objects can be converted into UmsPermission Long object. We often have this need: the need to id some objects extracted, and then to query other objects according to the id, then you can use this method.

// 获取所有权限的id组成的集合
List<Long> idList = permissionList.stream()
    .map(permission -> permission.getId())
    .collect(Collectors.toList());
复制代码

limit

Gets the specified number of elements from the Stream.

// 获取前5个权限对象组成的集合
List<UmsPermission> firstFiveList = permissionList.stream()
    .limit(5)
    .collect(Collectors.toList());
复制代码

count

Stream only get the number of elements.

// count操作:获取所有目录权限的个数
long dirPermissionCount = permissionList.stream()
    .filter(permission -> permission.getType() == 0)
    .count();
复制代码

sorted

Stream elements to be sorted by the specified rules.

// 将所有权限按先目录后菜单再按钮的顺序排序
List<UmsPermission> sortedList = permissionList.stream()
    .sorted((permission1,permission2)->{return permission1.getType().compareTo(permission2.getType());})
    .collect(Collectors.toList());
复制代码

skip

Stream skip a specified number of elements, the latter elements acquired.

// 跳过前5个元素,返回后面的
List<UmsPermission> skipList = permissionList.stream()
    .skip(5)
    .collect(Collectors.toList());
复制代码

Methods using collect converted into map List

Sometimes we need to repeatedly List objects in the query based on id, we can put the converted List for the key to the id of map structure, and then to get the object by map.get (id), so more convenient.

// 将权限列表以id为key,以权限对象为值转换成map
Map<Long, UmsPermission> permissionMap = permissionList.stream()
    .collect(Collectors.toMap(permission -> permission.getId(), permission -> permission));
复制代码

application

We often have to return the demand tree structure data. Such authority here, the first layer is the directory permissions, under the menu directory permissions have rights, rights under the menu button with permission. If we want to return to a collection that contains the directory permissions, directory permissions nested menu under authority, nested menu button Permissions permission. Use Stream API can easily solve this problem.

Note: to associate with pid between subordinate our rights here, pid refers to the id permissions on an id, the top authority of zero.

Object definition contains subordinate authority

UmsPermission inherited from the object, it adds a children attribute for storing the lower right.

/**
 * Created by macro on 2018/9/30.
 */
public class UmsPermissionNode extends UmsPermission {
    private List<UmsPermissionNode> children;

    public List<UmsPermissionNode> getChildren() {
        return children;
    }

    public void setChildren(List<UmsPermissionNode> children) {
        this.children = children;
    }
}

复制代码

The method of obtaining the definition of the tree structure

Let's filter out as the top authority pid 0, and then set its permissions to each top-level child rights, the main purpose is to find the appropriate method covert permission from all rights of child rights.

@Override
public List<UmsPermissionNode> treeList() {
    List<UmsPermission> permissionList = permissionMapper.selectByExample(new UmsPermissionExample());
    List<UmsPermissionNode> result = permissionList.stream()
            .filter(permission -> permission.getPid().equals(0L))
            .map(permission -> covert(permission, permissionList)).collect(Collectors.toList());
    return result;
}
复制代码

Set permissions for each child rights

Here we use a filter to filter out the operation permissions for each child of privilege, because the child may also have rights under sub-level permissions, here we use recursion to solve. But recursion when to stop, where the recursive call method to put the map operation, map operation when there is no child of privilege under the filter will no longer perform to stop the recursion.

/**
* 将权限转换为带有子级的权限对象
* 当找不到子级权限的时候map操作不会再递归调用covert
*/
private UmsPermissionNode covert(UmsPermission permission, List<UmsPermission> permissionList) {
    UmsPermissionNode node = new UmsPermissionNode();
    BeanUtils.copyProperties(permission, node);
    List<UmsPermissionNode> children = permissionList.stream()
           .filter(subPermission -> subPermission.getPid().equals(permission.getId()))
           .map(subPermission -> covert(subPermission, permissionList)).collect(Collectors.toList());
    node.setChildren(children);
    return node;
}
复制代码

Project Source Address

github.com/macrozheng/…

No public

mall project a full tutorial serialized in public concern number the first time to obtain.

No public picture

Guess you like

Origin juejin.im/post/5d6d2016e51d453c135c5b25