Java递归Java8流式处理 对父子节点结构集合数据的处理、并排序

实战

    @Test
    public void test01() {
        // 1、收集出 第一集的 数据
        List collect = list.stream()
                .filter((c) -> c.getParentNum() == 0)
                // 与map功能一致,对list中每一项循环转化,封装childrenList
                .peek((c) -> c.setChildren(getChildrenList(c.getNum(), list)))
                //排序操作
                .sorted(Comparator.comparingInt(StatisticsCenter::getTotal))
                .collect(Collectors.toList());
        collect.forEach(System.out::println);
    }

    //2、获取子节点集合
    public List getChildrenList(Integer pNum, List old) {
        return old.stream()
                .filter((c) -> pNum.equals(c.getParentNum()))
                .peek((c) -> c.setChildren(getChildrenList(c.getNum(), old)))
                .sorted(Comparator.comparingInt(StatisticsCenter::getTotal))
                .collect(Collectors.toList());
    }

@Data
@Accessors(chain = true)
class StatisticsCenter implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer id;
    private Integer num;
    private String title;
    private Integer parentNum;
    private Integer total;
    private List children;
}

实测,可以使用以下数据进行测试

数据准备:

Java递归Java8流式处理 对父子节点结构集合数据的处理、并排序_第1张图片

sql 可以去 码云上 获取: 

https://gitee.com/naimaohome/talk_about_fage.git

Java递归Java8流式处理 对父子节点结构集合数据的处理、并排序_第2张图片

数据封装:

    private static List list = new ArrayList<>();
    private Connection connection;
    private PreparedStatement statement;
    private ResultSet rs;

    @Before
    public void getAllData() throws SQLException {
        connection = DbUtil.getMysqlConnection();
        statement = connection.prepareStatement("select * from ba_statistics_center");
        rs = statement.executeQuery();
        while (rs.next()) {
            final StatisticsCenter center = new StatisticsCenter();
            center.setId(rs.getInt("id"))
                    .setNum(rs.getInt("num"))
                    .setTitle(rs.getString("title"))
                    .setParentNum(rs.getInt("parent_num"))
                    .setTotal(rs.getInt("total"));
            list.add(center);
        }
    }

    @After
    public void closeResource() throws SQLException {
        rs.close();
        statement.close();
        connection.close();
    }

    public static Connection getMysqlConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://192.168.0.44:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
            String username = "root";
            String password = "xxx";
            conn = DriverManager.getConnection(url, username, password);
            return conn;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

 

你可能感兴趣的:(Java,java,stream,lambda)