Skip to content

Commit

Permalink
Add SetUtils for creating ordered sets
Browse files Browse the repository at this point in the history
  • Loading branch information
bwaldvogel committed Nov 15, 2024
1 parent 67f1314 commit a74fbb8
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,23 @@ Set<Object> 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<String> ordered = SetUtils.orderedSet("abc", "def", "ghi");
// Output: [abc, def, ghi]

Set<Integer> numbers = SetUtils.orderedSet(3, 1, 2, 1);
// Output: [3, 1, 2]
```

> **Key Difference**: `SetUtils.orderedSet(…)` uses `LinkedHashSet`, ensuring insertion order is preserved.
## AlphanumericComparator

Expand Down
17 changes: 17 additions & 0 deletions src/main/java/de/cronn/commons/lang/SetUtils.java
Original file line number Diff line number Diff line change
@@ -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 <E> Set<E> orderedSet(E... elements) {
return new LinkedHashSet<>(Arrays.asList(elements));
}
}
19 changes: 19 additions & 0 deletions src/test/java/de/cronn/commons/lang/SetUtilsTest.java
Original file line number Diff line number Diff line change
@@ -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();
}

}

0 comments on commit a74fbb8

Please sign in to comment.