java組裝復雜的map結構

2024年2月6日 18点热度 0人点赞

有一個小的需求,如下圖數據庫查出來的記錄要組裝成如下圖所示的map結構。

直接上代碼

package com.rt.test.other;
import org.apache.commons.lang.StringUtils;
import java.util.*;
public class TestMap {
    public static void main(String[] args) {
        Map<String,String> map=new LinkedHashMap<>();
        List<Test> 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;
        }
    }
}

運行結果如圖: