英文:
Add two lists in java8?
问题
我正试图在Java 8中将两个列表相加。
这两个列表来自JSON中的不同对象,但我想在Java代码中将它们放到一个新对象中。
我已经尝试了listUtils.union,但这会将它们作为两个数组添加到新对象中。
addAll方法和stream.concat()也会导致错误。
示例:
JSON内容如下:
“对象1”:[{ test:”2”
}]
“对象2”:[{ test:”2”
}]
尝试将它们添加到一个HashMap中,放到对象“newobject”中,但我必须调用方法来获取这些新列表。
例如:
newlist = listUtils.Union(addobject1(), addObject1)(这些是从JSON中返回我的列表的方法名)。
put(“newobject”, newlist)
有任何建议吗?
英文:
I am trying to add two lists together in java 8.
Both lists are coming from separate objects in the json but I want to put them into a new object together in the java code.
I have tried listUtils.union but this is adding to the new object as two arrays.
The addAll method and stream .concat() are also giving errors.
Example:
Json has:
“Object 1”: [{ test:”2”
}]
“Object 2”: [{ test:”2”
}]
Trying to add to a hash map into the object “newobject” but I have to call methods to get the new lists.
For example :
Newlist = listUtils.Union(addobject1(), addObject1) (these are the method names that return my lists from the json.
put(“newobject”, newlist)
Any suggestions ?
答案1
得分: 1
根据JSON字符串,您有一些POJO的列表:
class MyPojo {
private final String test;
public MyPojo(String t) {
this.test = t;
}
public String getTest() {
return test;
}
@Override
public String toString() {
return "{ test: " + test + "}";
}
}
然后object1
和object2
是输入列表,有几种方法可以合并它们:
- 使用
Stream.concat
:
Stream.concat(object1.stream(), object2.stream()).collect(Collectors.toList());
- 使用
Stream.of
:
Stream.of(object1, object2)
.flatMap(List::stream)
.collect(Collectors.toList());
- 使用
addAll
:
List<MyPojo> result = new ArrayList<>(object1);
result.addAll(object2);
- 流式处理列表的列表:
Arrays.asList(object1, object2)
.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
英文:
According to the JSON string, you have lists of some POJO:
class MyPojo {
private final String test;
public MyPojo(String t) {this.test = t; }
public String getTest() {return test; }
@Override
public String toString() {
return "{ test: " + test + "}";
}
}
Then object1
and object2
are the input lists and there are several ways to merge them:
- Using
Stream.concat
Stream.concat(object1.stream(), object2.stream()).collect(Collectors.toList());
- Using
Stream.of
Stream.of(object1, object2)
.flatMap(List::stream)
.collect(Collectors.toList());
- Using
addAll
List<MyPojo> result = new ArrayList<>(object1);
result.addAll(object2);
- Streaming list of lists
Arrays.asList(object1, object2)
.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论