Home > Enterprise >  How to convert an object to a set?
How to convert an object to a set?

Time:10-11

so I have a set named "all" that contains objects Doc. Then I have another set called "partDocs" that contains other sets that contains Doc. Let's say that "all" contains = [Doc1, Doc2, Doc3]. I want partDocs to contain those sets like: [[Doc1], [Doc2], [Doc3]]. How can I do that?

I tried

Set<Doc> all = new HashSet<Doc>(); // contains [Doc1, Doc2, Doc3]
Set<Set<Doc>> partDocs = new HashSet<Set<Doc>>();
Set<Doc> set2 = new HashSet<Doc>();

for (i = 0; i < all.size(); i  ) {
   set2.clear();
   set2.add(all.stream().toList().get(i)); // adds the i.th element of the all set
   partDocs.add(set2);
}

However when I do this, partDocs only has the last element of the all set, because set2 is always changing, and its last value is [Doc3]

I also tried doing below, but its syntax is wrong

for (i = 0; i < all.size(); i  ) {
   partDocs.add(Set<allDocuments.stream().toList().get(i)>);
}

Does anyone have any idea about how to implement this?

CodePudding user response:

I don't know if you actually want to do this. It seems like very confusing code but try the following:

Set<Set<Doc>> partDocs = new HashSet<Set<Doc>>();
Set<Doc> all = new HashSet<>();

for(Doc doc : all) {
    partDocs.add(Set.of(doc));
}

And now you have a set (partDocs) that contains sets which contain docs

CodePudding user response:

The invalidation of set2 is flawed.

Instead of

set2.clear();

it should be

set2 = new HashSet<Doc>();

This particular bug may be easier to understand if we use a list for partDocs

List<Set<Doc>> partDocs = new ArrayList<Set<Doc>>();

which results in

[[Doc3], [Doc3], [Doc3]]

Essentially, we are adding the same Set to the List and since we are using the same reference, consecutive calls to set2.clear() and set2.add() will affect both the local variable and the Set in the List.

Going back to partDocs being a Set, it will end up with only one entry, because a Set guarantees to not contain duplicate values and three identical instances are of course duplicates.


So, to fix this bug, we must ensure that the three objects added to partDocs are truly distinct, which is accomplished (partly) by the new invalidation routine

set2 = new HashSet<Doc>();

and otherwise by the fact that we add a different element to it each time.

CodePudding user response:

Redeclare set2 in the loop.

        Set<Set<Doc>> partDocs = new HashSet<Set<Doc>>();
        for (int i = 0; i < all.size(); i  ) {
            Set<Doc> set2 = new HashSet<Doc>();
            set2.add(all.stream().toList().get(i)); // adds the i.th element of the all set
            partDocs.add(set2);
        }
  • Related