java组装复杂的map结构

 如下图数据库查出来的记录要组装成如下图所示的map结构。

java组装复杂的map结构_第1张图片

 直接上代码

package com.rt.test.other;

import org.apache.commons.lang.StringUtils;

import java.util.*;

public class TestMap {

    public static void main(String[] args) {
        Map map=new LinkedHashMap<>();
        List list=new ArrayList<>();
        list.add(new Test("###Chapter 1###",1));
        list.add(new Test("123",0));
        list.add(new Test("456",0));
        list.add(new Test("789",0));
        list.add(new Test("###Chapter 2###",1));
        list.add(new Test("abc",0));
        list.add(new Test("def",0));
        list.add(new Test("ghi",0));
        list.add(new Test("jkl",0));
        list.add(new Test("mno",0));
        String title=""; //标题
        StringBuilder content= new StringBuilder();//内容//内容
        for (Test test : list) {
            boolean b = test.getName().contains("###");
            Integer type = test.getFlag();//0 是标题 1是文章
            if(b){
                title=test.getName().replace("###","");
            }else if (type==0){
                content.append(test.getName()).append("-") ;
            }
            if(StringUtils.isNotBlank(content.toString())){
                map.put(title,content.substring(0,content.toString().length()-1));
            }
            //如果碰到标题,清空value
            if(type==1){
                content.setLength(0);
            }
        }
        System.out.println(map);
        //遍历LinkedHashMap key是文章章节标题,value是章节内容
        Set set = map.entrySet();
        for(Object key:set){
            Map.Entry entry = (Map.Entry) key;
            System.out.println("key:"+entry.getKey()+"----------value:"+entry.getValue());
        }
    }

    static class Test{
        private String name;

        private Integer flag;

        public Test(String name, Integer flag) {
            this.name = name;
            this.flag = flag;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getFlag() {
            return flag;
        }

        public void setFlag(Integer flag) {
            this.flag = flag;
        }
    }


}

运行结果如图:

{Chapter 1=123-456-789, Chapter 2=abc-def-ghi-jkl-mno}
key:Chapter 1----------value:123-456-789
key:Chapter 2----------value:abc-def-ghi-jkl-mno

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