猿问

如何创建动态列表<String>

我正在尝试动态创建一个列表


我尝试动态创建列表,但它不允许创建动态列表


int length = masterList.size();

for (int i = 0; i < length; i++) 

{

    for (Map.Entry < String, Object > entry: masterList.get(i).entrySet()) 

    {

        if(entry.getKey().startsWith("tag_"))

        {

            ArrayList<String> entry.getKey() = new ArrayList();

            tagDataList = Arrays.asList(entry.getValue().toString().split(","));

            for (String string : tagDataList) 

            {

                entry.getKey().add(string);

            }

        }

     }

}

输入:


{

 "tag_fuse_type": "tag_1,tag_2"

}

所需输出:


{

 "tag_fuse_type": [

  "tag_1",

  "tag_2"

 ]

}


白衣染霜花
浏览 104回答 2
2回答

精慕HU

Map<String, List<String>> newMap = new HashMap<>();for (Map.Entry<String, String> entry : masterList.entrySet()) {&nbsp; &nbsp; List<String> values = new LinkedList<>();&nbsp; &nbsp; if (entry.getKey().startsWith("tag_")) {&nbsp; &nbsp; &nbsp; &nbsp; String[] words = entry.getValue().split(",\\s*");&nbsp; &nbsp; &nbsp; &nbsp; Collections.addAll(values, words);&nbsp; &nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp; &nbsp; values.add(entry.getValue());&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;newMap.put(entry.getKey(), values);}一个不应该改变地图的类型,所以需要创建一个新的地图。

慕码人2483693

if (entry.getKey().startsWith("tag_")) {&nbsp; &nbsp; ArrayList < String > list = new ArrayList();&nbsp; &nbsp; tagDataList = Arrays.asList(entry.getValue().toString().split(","));&nbsp; &nbsp; for (String string: tagDataList) {&nbsp; &nbsp; &nbsp; &nbsp; list.add(string);&nbsp; &nbsp; }&nbsp; &nbsp; tagsMap.put(entry.getKey(), list);}
随时随地看视频慕课网APP

相关分类

Java
我要回答