Yankeecandle
Yankeecandle

Reputation: 1

Add two lists in java8?

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

Answers (1)

Nowhere Man
Nowhere Man

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:

  1. Using Stream.concat
Stream.concat(object1.stream(), object2.stream()).collect(Collectors.toList());
  1. Using Stream.of
Stream.of(object1, object2)
      .flatMap(List::stream)
      .collect(Collectors.toList());
  1. Using addAll
List<MyPojo> result = new ArrayList<>(object1);
result.addAll(object2);
  1. Streaming list of lists
Arrays.asList(object1, object2)
      .stream()
      .flatMap(List::stream)
      .collect(Collectors.toList());

Upvotes: 1

Related Questions