Home > database >  Return two Hashset from a Java method
Return two Hashset from a Java method

Time:12-31

I have this piece of code here that I want to transform in a method.

The problem is that I need the result of both hashes

How can I create a method that will return those two hashset (allPeopleFromTable and visibleInfo) ?

public method foo: 

Set<People> allPeopleFromTable = new HashSet<>();
        Set<People> visibleInfo = new HashSet<>();
        for (ResultSet rs : resultSets) {
            while (rs.next()) {
                final Table people = new Table(rs);

                allPeopleFromTable.add(people);
                if (isVisible(people)) {
                    visibleInfo.add(people);
                }
            }
        }

then in the main method I want to do
visibleInfo = getfoo(...)
allPeopleFromTable = getfoo (..)

CodePudding user response:

One option is to pass them into the method:

void foo(Set<People> allPeopleFromTable, Set<People> visibleInfo) {
    // add items to sets
}

Another option is return a list of sets:

List<Set<People>> foo() {
    // create sets
    return Arrays.asList(allPeopleFromTable, visibleInfo);
}

Or you can return a tuple class, like Entry:

Map.Entry<Set<People>, Set<People>> foo() {
    // create sets
    return Map.entry(allPeopleFromTable, visibleInfo);
}

The most "proper" approach would be to wrap them in a custom class.

record PeopleSets(Set<People> allPeopleFromTable, Set<People> visibleInfo) {}

PeopleSets foo() {
    // create sets
    return new PeopleSets(allPeopleFromTable, visibleInfo);
}

This example uses records, but you can use a conventional class if you're on an older version of Java.

  • Related