From a74fbb8da44fb7c07cdaafb877315c5805d5edb0 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Fri, 15 Nov 2024 09:21:08 +0100 Subject: [PATCH] Add SetUtils for creating ordered sets --- README.md | 17 +++++++++++++++++ .../java/de/cronn/commons/lang/SetUtils.java | 17 +++++++++++++++++ .../de/cronn/commons/lang/SetUtilsTest.java | 19 +++++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 src/main/java/de/cronn/commons/lang/SetUtils.java create mode 100644 src/test/java/de/cronn/commons/lang/SetUtilsTest.java diff --git a/README.md b/README.md index 029c023..5e72f28 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,23 @@ Set numbers = Stream.of(1, 2, 3, 2, 3) .collect(StreamUtil.toLinkedHashSet()); ``` +### SetUtils + +`SetUtils` provides utility methods for creating ordered sets in Java. + +Unlike `Set.of(…)`, `SetUtils.orderedSet(…)` maintains the order of elements as they are added. + +#### Example Usage + +```java +Set ordered = SetUtils.orderedSet("abc", "def", "ghi"); +// Output: [abc, def, ghi] + +Set numbers = SetUtils.orderedSet(3, 1, 2, 1); +// Output: [3, 1, 2] +``` + +> **Key Difference**: `SetUtils.orderedSet(…)` uses `LinkedHashSet`, ensuring insertion order is preserved. ## AlphanumericComparator diff --git a/src/main/java/de/cronn/commons/lang/SetUtils.java b/src/main/java/de/cronn/commons/lang/SetUtils.java new file mode 100644 index 0000000..5bb055f --- /dev/null +++ b/src/main/java/de/cronn/commons/lang/SetUtils.java @@ -0,0 +1,17 @@ +package de.cronn.commons.lang; + +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.Set; + +public final class SetUtils { + + private SetUtils() { + } + + @SafeVarargs + @SuppressWarnings("varargs") + public static Set orderedSet(E... elements) { + return new LinkedHashSet<>(Arrays.asList(elements)); + } +} diff --git a/src/test/java/de/cronn/commons/lang/SetUtilsTest.java b/src/test/java/de/cronn/commons/lang/SetUtilsTest.java new file mode 100644 index 0000000..f780536 --- /dev/null +++ b/src/test/java/de/cronn/commons/lang/SetUtilsTest.java @@ -0,0 +1,19 @@ +package de.cronn.commons.lang; + +import static org.assertj.core.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class SetUtilsTest { + + @Test + void testOrderedSet() { + assertThat(SetUtils.orderedSet("abc")).containsExactly("abc"); + assertThat(SetUtils.orderedSet("abc", "def", "ghi")).containsExactly("abc", "def", "ghi"); + assertThat(SetUtils.orderedSet(2, 1, 3)).containsExactly(2, 1, 3); + assertThat(SetUtils.orderedSet(2, 1, 3, 1)).containsExactly(2, 1, 3); + assertThat(SetUtils.orderedSet(null, "abc")).containsExactly(null, "abc"); + assertThat(SetUtils.orderedSet((Object) null)).singleElement().isNull(); + } + +}