Combining Two Different Lists Holding Different Objects in to Third List holding Object as Cross Join of Two Lists

Viewed 57

I have List of Objects. Each object holds a List of Long and a List of JsonNode. What I am trying to do is create a third List with Object, wherein each Object is the result of a cross join between the above two Lists.

E.g.

class MyClass{
    List<Long> _listLong;
    List<JsonNode> _listJsonNode;
}

I have List of MyClass Objects. What I want is to create a List of MyClass.

class MyClass2{
    Long id;
    JsonNode jsonNode;
}

such that List<MyClass2> holds the result of a cross join of List<Long> and List<JsonNode>.

I am able to do the same using loops. Is there a way to achieve the same using Streams in Java?

1 Answers

If you're starting with a list of MyClass objects, you have to flatten it and use two nested streams for the Cartesian product.

List<MyClass2> result = myClassList.stream().flatMap(
   mc -> mc.get_listLong()
                .stream()
                .flatMap(i -> mc.get_listJsonNode()
                                .stream()
                                .map(js -> new MyClass2(i, js))))
        .collect(Collectors.toList());

That assumes the constructor MyClass2(Long, JsonNode) exists. The inner flatMap is creating the required Cartesian product, by essentially iterating over all JsonNode elements for each Long element.

Related