KapreSoft
Thank you for unblocking ads; your support allows us to continue delivering free, high-quality content that truly matters to you.

Lombok @Singular Annotation

 
 

Overview

Lombok is a Java library that provides a set of annotations and utility classes to reduce boilerplate code in Java projects. One of its popular annotations is @Singular, which generates builder methods for collections.

Embed from Getty Images

What is @Singular?

When you annotate a collection field or parameter with @Singular, Lombok generates two methods for that collection: a method to add a single element to the collection, and a method to add multiple elements to the collection. These methods have names based on the singular and plural forms of the collection field or parameter. For example, if you annotate a field named items with @Singular, Lombok will generate an item method to add a single item and an items method to add multiple items.

For the reader’s convenience, the Singular.java can be found in the Source Code section of this article.

Here’s an Example in Java:

import lombok.Builder;
import lombok.Singular;

import java.util.List;

@Builder
public class Order {
    private final String orderId;
    @Singular private final List<String> items;
}

In this example, the Order class has a field named items that is annotated with @Singular. When you use the @Builder annotation to build an instance of Order, Lombok generates a builder() method that you can use to add items to the items field. Here’s an example of how to use the builder:

Order order = Order.builder()
        .orderId("123")
        .item("item1")
        .item("item2")
        .items(List.of("item3", "item4"))
        .build();

@Singular Options

The @Singular annotation from Lombok has a few other options that can be used to customize the behavior of the generated methods:

value

This option allows you to specify a custom name for the singular method that adds a single element to the collection. By default, Lombok generates this method based on the name of the annotated field.

Example:

import lombok.Builder;
import lombok.Singular;

import java.util.List;

@Builder
public class Order {
    private final String orderId;
    @Singular("addItem") private final List<String> items;
}

With this option, the singular method for adding an item to the items list will be named addItem() instead of item().

ignoreNullCollections

This option allows you to specify whether or not to generate methods for adding elements to the collection if the collection is null. If this option is set to true, Lombok will skip generating the methods if the collection is null.

Example:

import lombok.Builder;
import lombok.Singular;

import java.util.List;

@Builder
public class Order {
    private final String orderId;
    @Singular(ignoreNullCollections = true) private final List<String> items;
}

With this option set to true, Lombok will not generate the singular and plural methods for the items list if it is null.

ignoreEmptyCollections

This option allows you to specify whether or not to generate methods for adding elements to the collection if the collection is empty. If this option is set to true, Lombok will skip generating the methods if the collection is empty.

import lombok.Builder;
import lombok.Singular;

import java.util.List;

@Builder
public class Order {
    private final String orderId;
    @Singular(ignoreEmptyCollections = true) private final List<String> items;
}

With this option set to true, Lombok will not generate the singular and plural methods for the items list if it is empty.

suppressWarnings

This option allows you to suppress any warnings that may be generated by the @Singular annotation.

import lombok.Builder;
import lombok.Singular;

import java.util.List;

@Builder
@SuppressWarnings("lombok:Singular") // suppress any warnings that may be generated
public class Order {
    private final String orderId;
    @Singular private final List<String> items;
}

With this option set, any warnings generated by the @Singular annotation will be suppressed.

These options can be used individually or in combination to customize the behavior of the @Singular annotation in Lombok.

What else is important about @Singular?

There are a few more things you may need to know about the @Singular annotation from Lombok:

Defensive Copies

@Singular generates defensive copies of collections by default. This means that the methods generated by @Singular will create a new copy of the collection before adding or removing elements, which helps prevent unwanted modifications to the original collection.

Collections

The @Singular annotation works with several types of collections, including List, Set, and Map.

Map Fields

When using @Singular with Map fields, you can specify the names of the singular and plural methods for adding and removing entries by using the key and entry options.

For example:

import lombok.Builder;
import lombok.Singular;

import java.util.Map;

@Builder
public class Order {
    private final String orderId;
    @Singular private final Map<String, Integer> items;
}

In this example, the items field is a Map of strings to integers, and @Singular will generate methods for adding and removing entries from the map using the default names item() and items().

If you want to use custom names, you can use the key and entry options to specify them:

import lombok.Builder;
import lombok.Singular;

import java.util.Map;

@Builder
public class Order {
    private final String orderId;
    @Singular(key = "itemName", entry = "quantity") private final Map<String, Integer> items;
}

In this example, the @Singular annotation is configured to use the names itemName() and quantities() for adding and removing entries from the map, respectively.

Custom Collection Types

@Singular can be used with custom collection types that have a single-argument add method. If you have a custom collection type with a different method for adding elements, you can use the method option to specify its name:

import lombok.Builder;
import lombok.Singular;

import java.util.Deque;

@Builder
public class Order {
    private final String orderId;
    @Singular(method = "push") private final Deque<String> items;
}

In this example, the @Singular annotation is configured to use the push() method of a Deque to add elements to the collection.

These are some additional details about the @Singular annotation that you may find useful when working with Lombok.

In Conclusion

In conclusion, the @Singular annotation from Lombok is a handy tool that simplifies the process of creating and modifying collections in your Java code. By using this annotation, you can generate concise and easy-to-use methods for adding and removing elements from collections, such as lists, sets, maps, and custom collection types. Additionally, the @Singular annotation has various options that allow you to customize the names and behavior of the generated methods to suit your needs. Whether you’re a beginner or an experienced programmer, @Singular can save you time and effort when working with collections.

Source Code

Here is a snapshot of the Singular.java annotation source code:


Lombok • The Good, The Bad, and The Ugly
Within the Java development community, Lombok often emerges as a polarizing subject. This library’s chief aim is to minimize the tedium of boilerplate code—a persistent thorn in the side of many Java developers. Nevertheless, every tool brings its own concessions to the table.
Lombok • @Value Annotation Best Practices
When it comes to clean coding and enhanced testability in Java applications, Project Lombok is a game-changer. Its @Value annotation not only simplifies your code but also enhances its readability, maintainability, and testability.
Lombok • @Data Annotation Best Practices
When it comes to clean and efficient Java coding, the power of Project Lombok cannot be overstated. Specifically, the @Data annotation provided by Lombok stands out as a valuable tool for Java developers.
Cleaner Code and Enhanced Testability: Harnessing the Power of Lombok Builders
In the realm of Java development, the quest for cleaner code and improved testability is ever-present. One formidable ally in this quest is Project Lombok, a mature library that revolutionizes the way Java developers handle boilerplate code.
Lombok val vs var
Lombok has gained immense popularity among Java developers for its ability to simplify coding practices by reducing boilerplate code. In the vast ocean of features offered by Lombok, two features stand out: val and var. In this deep dive, we’ll uncover the secrets of these two variables and demonstrate their utility.
Lombok Test Coverage
When it comes to software development, testing plays a crucial role in ensuring the quality and reliability of the codebase. Test coverage, in particular, is a metric that measures the extent to which the source code of a program has been tested.
Lombok Disadvantages
In the world of Java development, optimizing code efficiency and reducing boilerplate is a constant pursuit. To address these challenges, various tools and libraries have emerged, and one such popular option is Lombok—a Java library that offers annotations for code generation, resulting in benefits such as time-saving and code simplification. However, as with any tool, there are both advantages and drawbacks to consider.
Java • Avoid Getters & Setters Methods With Lombok
This article provides an overview of how to avoid the repetitive code associated with writing getter and setter methods in Java classes using Lombok. By using Lombok’s annotations, such as @Getter and @Setter, developers can generate these methods automatically, thereby reducing the amount of boilerplate code required in their classes.
Lombok • @AllArgsConstruct vs @RequiredArgsConstructor
What is the difference between @AllArgsConstruct and @RequiredArgsConstructor in Lombok? The main difference between @AllArgsConstructor and @RequiredArgsConstructor is in the fields that are included in the generated constructor.
Lombok • How to Use Constructor
To use the constructor with Lombok, you can annotate your class with @AllArgsConstructor or @RequiredArgsConstructor. @AllArgsConstructor generates a constructor that takes in all the fields in the class as arguments, while @RequiredArgsConstructor generates a constructor that takes in only the final or @NonNull fields as arguments.
Lombok • An Overview
Lombok is a Java library that provides annotations to help reduce boilerplate code and increase developer productivity. By using Lombok annotations, Java developers can automatically generate common code such as getters, setters, constructors, equals and hashCode methods, and more.
Lombok • Exclude Generated Code From Test Coverage
When using Lombok in a Java project, the library generates code at compile-time, such as getters, setters, constructors, equals and hashCode methods, and more.
Lombok • Using @With Annotation to Clone Immutable Objects
Using Lombok’s @With Annotation to Clone Immutable Objects is a beneficial feature that helps developers minimize code replication and ceremonial code. It is the next best alternative to Copy Constructs in object-oriented programming. The @With annotation also requires @AllArgsConstructor to function correctly.
Lombok • Builders and Copy Constructors
Lombok’s builder and copy constructor feature using @Builder is a mechanism that allows the implementation of the Builder Pattern and Copy Constructors in Object-Oriented Programming. This article further illustrates how Lombok mitigates the disadvantages of creating builder methods and copy constructors making Lombok’s @Builder a good foundation for design and code maintainability.