英文:
How to write lambda streams function to work with jsonobject with different keys and json array
问题
Here's the code you provided translated into Chinese:
我对Java 8的lambda表达式非常陌生... 我想要编写一个lambda函数,它接受一个JSONArray,遍历其中的JSONObjects并创建某个字段的Json对象。
例如,一个接受JSONArray的函数:
"students": [
{
"name": "tom",
"section": "A",
"language":"english"
},
{
"name": "john",
"section": "B",
"language":"dutch"
},
{
"name": "sam",
"section": "C",
"language":"spanish"
}]
我的输出应该如下所示-
nameJson : {"english":"tom","dutch":"john","spanish":"sam"}
sectionJson: {"english":"A","dutch":"B","spanish":"C"}
```java
JSONArray notification=json.optJSONArray("studentData");
JSONObject nameJson = new JSONObject();
JSONObject sectionJson=new JSONObject();
for (int i=0;i<notification.length();i++){
nameJson.put(notification.getJSONObject(i).get("language").toString(),notification.getJSONObject(i).get("name").toString());
sectionJson.put(notification.getJSONObject(i).get("language").toString(),notification.getJSONObject(i).getString("section").toString());
}
请帮助我使用lambda和流编写此代码。
请注意,代码中的HTML编码已被移除以便更好地阅读。
<details>
<summary>英文:</summary>
I'm very new to Java 8 lambdas... I want to write a lambda function that takes a JSONArray, goes over its JSONObjects and creates a Json object of certain field.
For example, a function that takes the JSONArray:
"students": [
{
"name": "tom",
"section": "A",
"language":"english"
},
{
"name": "john",
"section": "B",
"language":"dutch"
},
{
"name": "sam",
"section": "C",
"language":"spanish"
}]
My output should be like-
nameJson : {"english":"tom","dutch":"john","spanish":"sam"}
sectionJson: {"english":"A","dutch":"B","spanish":"C"}
JSONArray notification=json.optJSONArray("studentData");
JSONObject nameJson = new JSONObject();
JSONObject sectionJson=new JSONObject();
for (int i=0;i<notification.length();i++){
nameJson.put(notification.getJSONObject(i).get("language").toString(),notification.getJSONObject(i).get("name").toString());
sectionJson.put(notification.getJSONObject(i).get("language").toString(),notification.getJSONObject(i).getString("section").toString());
}
Please help me out to write using lambda and streams
</details>
# 答案1
**得分**: 1
以下是您要的中文翻译部分:
将for循环转换为Stream的简单方法是使用IntStream和forEach方法。解决方案取决于您使用的JSON库版本。旧版本会在Lambda内部引发需要处理的异常,类似于以下内容:
```java
JSONObject nameJson = new JSONObject();
JSONObject sectionJson = new JSONObject();
IntStream.range(0, notification.length()).forEach(index -> {
try {
nameJson.put(notification.getJSONObject(index).get("language").toString(), notification.getJSONObject(index).get("name").toString());
sectionJson.put(notification.getJSONObject(index).get("language").toString(), notification.getJSONObject(index).get("section").toString());
} catch (JSONException e) {
throw new RuntimeException(e);
}
});
较新版本的JSON库在get方法上不会引发异常,与org.json:json:20230227版本一起使用的示例代码如下:
JSONObject nameJson = new JSONObject();
JSONObject sectionJson = new JSONObject();
IntStream.range(0, notification.length()).mapToObj(notification::getJSONObject).forEach(jsonObject -> {
nameJson.put(jsonObject.getString("language"), jsonObject.getString("name"));
sectionJson.put(jsonObject.getString("language"), jsonObject.getString("section"));
});
执行反向操作,假设您有nameJson和sectionJson对象,您可以尝试以下操作(适用于org.json:json的最新版本):
List<JSONObject> jsonObjectList = nameJson.keySet().stream().map(language -> {
JSONObject notificationJson = new JSONObject();
notificationJson.put("name", nameJson.getString(language));
notificationJson.put("section", sectionJson.getString(language));
return notificationJson.put("language", language);
}).collect(Collectors.toList());
JSONArray notificationsJson = new JSONArray().putAll(jsonObjectList);
英文:
Simple way to convert a for loop into Stream is to use IntStream with forEach method. The solution defers based on the version of JSON Library that you are using. Older version throws exception that needs to be handled within the Lambda, something like below:
JSONObject nameJson = new JSONObject();
JSONObject sectionJson=new JSONObject();
IntStream.range(0, notification.length()).forEach(index -> {
try {
nameJson.put(notification.getJSONObject(index).get("language").toString(),notification.getJSONObject(index).get("name").toString());
sectionJson.put(notification.getJSONObject(index).get("language").toString(),notification.getJSONObject(index).get("section").toString());
} catch (JSONException e) {
throw new RuntimeException(e);
}
});
Newer version of the JSON Library does not throw Exception on get method, sample code that works with org.json:json:20230227 version looks like below:
JSONObject nameJson = new JSONObject();
JSONObject sectionJson=new JSONObject();
IntStream.range(0, notification.length()).mapToObj(notification::getJSONObject).forEach(jsonObject -> {
nameJson.put(jsonObject.getString("language"),jsonObject.getString("name"));
sectionJson.put(jsonObject.getString("language"),jsonObject.getString("section"));
});
For performing reverse, assuming that you have nameJson and sectionJson objects handy you can try something like (works with latest version of org.json:json):
List<JSONObject> jsonObjectList = nameJson.keySet().stream().map(language -> {
JSONObject notificationJson = new JSONObject();
notificationJson.put("name", nameJson.getString(language));
notificationJson.put("section", sectionJson.getString(language));
return notificationJson.put("language", language);
}).collect(Collectors.toList());
JSONArray notificationsJson = new JSONArray().putAll(jsonObjectList);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论