Search code examples
javagenericsdesign-patterns

Make a java method return different objects in one single call


I have a java method which has to return both List<ObjectA> and a List<List<String>> for each and every call made to it.

One way I can think of achieving this is by returning Map<String, Object> where string will be key and object will be my lists. But I think returning a Map is not an elegant way of doing so in my scenario. Any help with this?


Solution

  • With Java 14+, we have the possibility to use Records (JEP 395, openjdk.org). Without knowing anything of the semantics, I will demonstrate the usage with a generic record Pair, but we can of course always find more descriptive names.

    We define a generic Pair of generic types T and U:

    record Pair<T, U> (T first, U second) {}
    

    And a dummy-implementation of ObjectA:

    class ObjectA {
      private final String name;
    
      public ObjectA(String name) {
        this.name = name;
      }
    
      @Override
      public String toString() {
        return "ObjectA{" +
            "name='" + name + '\'' +
            '}';
      }
    }
    

    We can then implement our method like this:

    public static Pair<List<ObjectA>, List<List<String>>> foo() {
      return new Pair<>(
          List.of(new ObjectA("one"), new ObjectA("two")),
          List.of(
              List.of("three", "four"),
              List.of("five", "six"),
              List.of("seven", "eight")));
    }
    

    And call it like this:

    var fooResult = foo();
    System.out.println(fooResult.first()); // prints the List<ObjectA>
    System.out.println(fooResult.second()); // prints the List<List<String>>
    System.out.println(fooResult);
    

    This would produce the following output:

    [ObjectA{name='one'}, ObjectA{name='two'}]
    [[three, four], [five, six], [seven, eight]]
    Pair[first=[ObjectA{name='one'}, ObjectA{name='two'}], second=[[three, four], [five, six], [seven, eight]]]
    

    (Sorry, no Ideone.com demo, Ideone does not support Java 14+, only Java 12)