Java 8: How to write lambda stream to work with JsonArray?

后端 未结 3 1037
谎友^
谎友^ 2020-12-17 21:26

I\'m very new to Java 8 lambdas and stuff... I want to write a lambda function that takes a JsonArray, goes over its JsonObjects and creates a list of values of certain fiel

3条回答
  •  清歌不尽
    2020-12-17 22:00

    Yes, I recognized that result of put is being added to json array instead of json object. Should be like this.

    private static JSONObject getJson(String key, String value){
        JSONObject result = new JSONObject();
        result.put(key, value);
        return result;        
    }
    
    public static void main(String[] args) {
        JSONArray jsonArray = new JSONArray();
    
        jsonArray.add(getJson("name", "John"));
        jsonArray.add(getJson("name", "David"));
    
        List list = (List) jsonArray.stream()
                    .map(json -> json.toString())
                    .collect(Collectors.toList());
        System.out.println(list);
    }
    

    and output is now [{"name":"John"}, {"name":"David"}] like expected

提交回复
热议问题