你会如何在java 8流上进行多项操作?

obe*_*n13 10 java java-stream

例如,您有一个要转换为JSONObject的pojo列表.你有一个pojo列表.但是为了转换为JSONObject,您需要使用JSONObject put方法.

JSONObject personJson = new JSONObject();
for(Person person : personList){
   personJson.put("firstName", person.firstName);
   personJson.put("lastName", person.lastname);
   ...
}
Run Code Online (Sandbox Code Playgroud)

如果它只是我想做的一项操作,那么我就可以做到

personList.stream.map(personJson.put("firstName", person.firstName));
Run Code Online (Sandbox Code Playgroud)

Kar*_*waj 7

 JSONArray array=new JSONArray();
        personList.stream().forEach(element ->
        {
            JSONObject personJson = new JSONObject();
            personJson.put("firstName", element.firstName);
            personJson.put("lastName", element.lastname);
            array.add(personJson);
        });
Run Code Online (Sandbox Code Playgroud)

  • http://stackoverflow.com/questions/20375176/should-i-always-use-a-parallel-stream-when-possible - 不要只是毫不犹豫地使用并行流! (6认同)

Mar*_*ter 6

此处提到的解决方案虽然有效,但它们是在流上下文之外对对象进行突变,应避免这种情况。

因此,.forEach()终止操作而不是使用return void。正确的方法是使用.map()它,正如其名称所说,将一个值映射到另一个值。在您的情况下,您要执行的第一个操作是将Person映射到JSONObject。第二个操作是一个reducer函数,您想在其中将所有JSONObject缩减为一个JSONArray对象。

public JSONArray mapListToJsonArray(List<Person> persons) {
    List<JSONObject> jsonObjects = persons
            .stream()
            .map(person -> {
                JSONObject json = new JSONObject();
                json.put("firstName", person.getFirstName());
                json.put("lastName", person.getLastName());
                return json;
            })
            .collect(Collectors.toList());
    return new JSONArray(jsonObjects);
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,JSONArray的json.org实现没有轻松合并两个数组的方法。因此,我没有将其简化为JSONArray,而是首先将所有JSONObjects收集为一个列表,然后从中创建一个JSONArray。

如果将lambda表达式替换为方法引用,则解决方案看起来更好。

public JSONArray mapListToJsonArray(List<Person> persons) {
    List<JSONObject> jsonObjects = persons
            .stream()
            .map(this::mapPersonToJsonObject)
            .collect(Collectors.toList());
    return new JSONArray(jsonObjects);
}

public JSONObject mapPersonToJsonObject(Person person) {
    JSONObject json = new JSONObject();
    json.put("firstName", person.getFirstName());
    json.put("lastName", person.getLastName());
    return json;
}
Run Code Online (Sandbox Code Playgroud)