JSONArrayをマップに実装する3つの方法

この記事は、私が一般的に使用している3つだけです。これらの3つだけでなく、自分で要約します。

JSONArrayデータ

[
    {
        "flagType": 1,
        "flagIcon": "1.jpg"
    },
    {
        "flagType": 2,
        "flagIcon": "2.jpg"
    },
    {
        "flagType": 3,
        "flagIcon": "3.jpg"
    },
    {
        "flagType": 4,
        "flagIcon": "4.jpg"
    }
]

ターゲットデータに変換する

{
    1:"1.jpg",
    2:"2.jpg",
    3:"3.jpg",
    4:"4.jpg"
}

 最初

JSONArray jsonArray= new JSONArray();
//填充初始数据,此处过程省略
List<JSONObject> jsonObjectList = jsonArray.toJavaList(JSONObject.class);
Map<Integer, String> map = jsonObjectList.stream().filter(Objects::nonNull).collect(Collectors.toMap(item -> item.getInteger("flagType"), item -> item.getString("flagIcon")));

 二番目 

JSONArray jsonArray= new JSONArray();
//填充初始数据,此处过程省略
Map<Integer, String> map = jsonArray.stream().filter(Objects::nonNull)
                .collect(Collectors.toMap(
                        object -> {
                            JSONObject item = (JSONObject) object;
                            return item.getInteger("flagType");
                        },
                        object -> {
                            JSONObject item = (JSONObject) object;
                            return item.getString("flagIcon");
                        }
                ));

第3 

Map<Integer, String> flagIconMap = new HashMap<>();

JSONArray jsonArray= new JSONArray();
//填充初始数据,此处过程省略
if (jsonArray != null && !jsonArray.isEmpty()) {
	jsonArray.forEach(object -> {
		if (object == null) {
			return;
		}
		JSONObject jsonObject = (JSONObject) object;
		if (jsonObject.getInteger("flagType") == null) {
			return;
		}
    	flagIconMap.put(jsonObject.getInteger("flagType"),jsonObject.getString("flagIcon"));
	});
}

 

おすすめ

転載: blog.csdn.net/weixin_43075027/article/details/109533803