Quickly implement a singleton with an enum in Java

In the past, I used to use Initialize-On-Demand Holder, but recently I have made a singleton with enum. Below is an example of a string utility class.

Implementation example

Basically, create an enum that also has the only element, ʻINSTANCE`, All you have to do now is create the public method normally. It's easy and easy.

StringUtility.java


package jp.fumokmm;

import java.util.Objects;

public enum StringUtility {
	INSTANCE;

	/**
	 * <p>Trims the specified string.
	 *If the specified string is null, an empty string will be returned.</p>
	 * @param str string to trim
	 * @return String after trimming
	 */
	public String trim(String str) {
		return Objects.nonNull(str) ? str.trim() : "";
	}

	/**
	 * <p>Trims the specified character string (including double-byte spaces).
	 *If the specified string is null, an empty string will be returned.</p>
	 * @param str string to trim
	 * @return String after trimming
	 */
	public String trimFull(String str) {
		if (Objects.isNull(str)) return "";
		int len = str.length();
		int st = 0;
		char[] val = str.toCharArray();
		while (st < len && (val[st] <= ' ' || val[st] == ' ')) {
			st++;
		}
		while (st < len && (val[len - 1] <= ' ' || val[len - 1] == ' ')) {
			len--;
		}
		return (st > 0 || len < str.length()) ? str.substring(st, len) : str;
	}

}

Usage example

StringUtilityTest.java


package jp.fumokmm;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import org.junit.Test;

public class StringUtilityTest {

	@Test
	public void testTrim() {
		StringUtility util = StringUtility.INSTANCE;
		assertThat(util.trim(null), is(""));
		assertThat(util.trim(" "), is(""));
		assertThat(util.trim(" a "), is("a"));
		assertThat("Full-width space is not trimmed", util.trim("  a  "), is("  a  "));
	}

	@Test
	public void testTrimFull() {
		StringUtility util = StringUtility.INSTANCE;
		assertThat(util.trimFull(null), is(""));
		assertThat(util.trimFull(" "), is(""));
		assertThat(util.trimFull(" a "), is("a"));
		assertThat("Full-width space is also trimmed", util.trimFull("  a  "), is("a"));
	}

}

By the way, in the above test

StringUtility util = StringUtility.INSTANCE;

I use it after assigning it to a variable once like

StringUtility.INSTANCE.trim(str);

You can use it as it is. Please check the readability and use it.

that's all.

Recommended Posts

Quickly implement a singleton with an enum in Java
3 Implement a simple interpreter in Java
Implement something like a stack in Java
Split a string with ". (Dot)" in Java
I want to ForEach an array with a Lambda expression in Java
GetInstance () from a @Singleton class in Groovy from Java
Read a string in a PDF file with Java
Create a CSR with extended information in Java
Stuck in an enum in front of a blacksmith
Output true with if (a == 1 && a == 2 && a == 3) in Java (Invisible Identifier)
Why implement with a singleton instead of a static method
Implement two-step verification in Java
Implement Basic authentication in Java
Find a subset in Java
Implement math combinations in Java
Enum Strategy pattern in Java
2 Implement simple parsing in Java
Implement Email Sending in Java
Implement functional quicksort in Java
Reproduce Java enum in C #
Implement rm -rf in Java.
Implement XML signature in Java
Implementing a large-scale GraphQL server in Java with Netflix DGS
Create a SlackBot with AWS lambda & API Gateway in Java
Easily get an integer from a system property in Java
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
Get a non-empty collection from an Optional stream in java
Create an immutable class with JAVA
Implement Table Driven Test in Java 14
I sent an email in Java
Build a Java project with Gradle
Morphological analysis in Java with Kuromoji
[Java EE] Implement Client with WebSocket
[Java] Branch enum with switch statement
I created a PDF in Java.
Create a high-performance enum with fields and methods like Java with JavaScript
How to implement a job that uses Java API in JobScheduler
Sorting a list with an int array as an element (Java) (Comparator)
Implement reCAPTCHA v3 in Java / Spring
Implement PHP implode function in Java
Try an If expression in Java
[Java] How to search for a value in an array (or list) with the contains method
Implement a gRPC client in Ruby
A simple sample callback in Java
Implement a contact form in Rails
Cast an array of Strings to a List of Integers in Java
[Java] Reduce if statements with Enum
I made an annotation in Java.
Formatting an enum using formatter-maven-plugin (Java)
Java Calendar is not a singleton.
Try to implement Yubaba in Java
Get stuck in a Java primer
1 Implement simple lexical analysis in Java
Play with Markdown in Java flexmark-java
Run an application made with Java8 with Java6
Run an external process in Java
[Personal memo] How to interact with a random number generator in Java
[Java] How to turn a two-dimensional array with an extended for statement
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (PowerMockito edition)
I wanted to implement a slide show in a fashionable way with slick.
I wrote a Lambda function in Java and deployed it with SAM