Reputation: 1
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 ?
Upvotes: -3
Views: 508
Reputation: 19565
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:
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());
Upvotes: 1