flatMap和双重for循环的优劣--是否有必要使用flatMap

前几天看同事的代码,发现他有个地方用了java8的flatMap扁平化流来处理两个集合的交集并集。我就测了一下,是否有必要这样做。
接下来我们看一下,首先有两个实体类,第一个实体类是user类

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class SysUser implements Serializable {

    private static final long serialVersionUID=1L;

    /**
     * 用户ID
     */
    @TableId(value = "user_id", type = IdType.AUTO)
    private Long userId;

    /**
     * 部门ID
     */
    private Long deptId;

    /**
     * 登录账号
     */
    private String loginName;

    /**
     * 用户昵称
     */
    private String userName;


    /** 角色组 */
    private Long[] roleIds;

    /** 岗位组 */
    private Long[] postIds;
 
}

第二个实体类,用户角色类

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysUserRole implements Serializable {

    private static final long serialVersionUID=1L;

    /**
     * 用户ID
     */
    private Long userId;

    /**
     * 角色ID
     */
    private Long roleId;


}

然后新增一个单元测试,有userList集合,和一个userRoleList集合,此时,当user集合中的id与userRole集合中userId相等的值取出来。以下测试一个用的flatMap,另一个用的双重for循环。

package com.example.shardingSphere;


import com.example.shardingSphere.entity.SysUser;
import com.example.shardingSphere.entity.SysUserRole;
import com.example.shardingSphere.entity.UserRoleDeptListVO;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liushan
 * @since 19:34
 */
public class FlatMapTest {
    public static void main(String[] args) {
        List<SysUser> userList = new ArrayList<>();
        SysUser sysUser = new SysUser();
        sysUser.setUserId(1L);
        sysUser.setUserName("jiuo");
        SysUser sysUser1 = new SysUser();
        sysUser1.setUserId(2L);
        sysUser1.setUserName("hahahha");
        userList.add(sysUser);
        userList.add(sysUser1);
        List<SysUserRole> userRoleList = new ArrayList<>();
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId(2L);
        sysUserRole.setUserId(1L);
        userRoleList.add(sysUserRole);
        long l = System.currentTimeMillis();
        List<UserRoleDeptListVO> userRoleDeptListVOS = userList.stream().flatMap(user -> {
            return userRoleList.stream().filter(role -> role.getUserId() == user.getUserId())
                    .map(userrole -> {
                        return new UserRoleDeptListVO(user.getUserId(), userrole.getRoleId(), user.getDeptId(), user.getUserName());
                    });
        }).collect(Collectors.toList());
        long l2 = System.currentTimeMillis();
        System.out.println("flatMap花费的时间:  " + (l2 - l));
        System.out.println(userRoleDeptListVOS);
        long l3 = System.currentTimeMillis();
        List<UserRoleDeptListVO> userRoleDeptListVOS1 = new ArrayList<>();
        for (SysUser user : userList) {
            for (SysUserRole userRole : userRoleList) {
                if (user.getUserId() == userRole.getUserId()) {
                    UserRoleDeptListVO userRoleDeptListVO = new UserRoleDeptListVO(user.getUserId(), userRole.getRoleId(), user.getDeptId(), user.getUserName());
                    userRoleDeptListVOS1.add(userRoleDeptListVO);
                }
            }
        }
        long l4= System.currentTimeMillis();
        System.out.println("for花费的时间:  " + (l4 - l3));
        System.out.println(userRoleDeptListVOS1);
    }
}

得到的结果为
在这里插入图片描述
flatMap花的时间为50-100ms左右,而双重for循环一直是5ms以下。

现在大家都提倡用stream,但明显并不是都适合。代码并不是追求高大上,而是效率,质量。

猜你喜欢

转载自blog.csdn.net/weixin_42328375/article/details/106627987