Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE] @Singular Map with Immutable Collection #3832

Open
KyRobbins opened this issue Feb 20, 2025 · 0 comments
Open

[FEATURE] @Singular Map with Immutable Collection #3832

KyRobbins opened this issue Feb 20, 2025 · 0 comments

Comments

@KyRobbins
Copy link

KyRobbins commented Feb 20, 2025

Currently you can use @Singular on a Map to produce an immutable Map with convenient methods on the builder for adding a single entry. If you were to do a Map<?, Collection<?>>, this also works, offering a method to add a collection as a single entry for the builder, but what about adding a single item to a possibly existing collection, and making that collection immutable?

There are other ways it could be done, you could track a Collection<?> as a separate element and add it to a builder only once it is completed, but I think it would be nice to maintain the builder as the primary mechanism

Example:

@Builder
public class Context {
  @Singular
  private final Map<String, List<Constraint>> groupConstraints;
}
//...
private void parseNode(Context.ContextBuilder builder, Node node) {
  //...
  node.getConstraints().stream().forEach(constraint -> builder.addGroupConstraint(constraint.getGroup(), constraint));
  //...
}

Possible Sample Builder Code:

public Context.ContextBuilder groupConstraint(String key, List<Constraint> constraints) {
  if (this.groupConstraints$key == null) {
    this.groupConstraints$key = new ArrayList();
    this.groupConstraints$value = new ArrayList();
  }

  this.groupConstraints$key.add(key);
  this.groupConstraints$value.add(constraints);
}

public Context.ContextBuilder groupConstraint(String key, Constraint constraint) {
  if (this.groupConstraints$key == null) {
    this.groupConstraints$key = new ArrayList();
    this.groupConstraints$value = new ArrayList();
  }

  int lastIndex = this.groupConstraints$key.lastIndexOf(key);

  if (lastIndex > -1) {
    this.groupConstraints$value.get(lastIndex).add(constraint);
  } else {
    this.groupConstraints$key.add(key);
    this.groupConstraints$value.add(constraints);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant