liveBook · Manning

Set

As explained in Spring in Action, Sixth Edition

A set is a collection that stores distinct elements without permitting duplicates.

A set is a collection of distinct elements: adding the same element again does not create a duplicate. In reactive persistence, a Taco uses a set of ingredient IDs to guarantee that each ingredient appears only once. section 13.1.1

A set is useful when:

  • Uniqueness matters, such as preventing the same ingredient from being added twice. section 13.1.1
  • The collection represents references rather than complete related entities; Taco stores Set<Long> ingredient IDs. section 13.1.1

Adding taco ingredients

A Taco initializes ingredientIds with HashSet<>. Its addIngredient method adds an ingredient's ID, so repeated additions of the same ID remain a single entry.

Listing 13.2 The Taco entity class for R2DBC persistence
package tacos;
 
import java.util.HashSet;
import java.util.Set;
import org.springframework.data.annotation.Id;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
 
@Data
@NoArgsConstructor
@RequiredArgsConstructor
public class Taco {
 
  @Id
  private Long id;
  
  private @NonNull String name;
  
  private Set<Long> ingredientIds = new HashSet<>();
  
  public void addIngredient(Ingredient ingredient) {
    ingredientIds.add(ingredient.getId());
  }
  
}

Inspect the complete Taco entity, including its Set<Long> collection and addIngredient method. section 13.1.1

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains uniqueness, HashSet initialization, ID references, and array persistence, but does not develop set internals.
Examples
Demonstrates Set<Long> ingredient IDs in Taco and an ingredient_ids database array.
What it assumes
Assumes basic Java entities and identifiers while demonstrating set usage through a Taco persistence model.
What you can do after
Apply sets via Java HashSet to prevent duplicate ingredient IDs in a Spring Data R2DBC entity.
How it connects
Connects sets with collections, entity relationships, identifiers, and reactive persistence.

Also explained in

Compare how 15 books explain set →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.