diff --git a/li.strolch.utils/src/main/java/li/strolch/utils/collections/CollectionsHelper.java b/li.strolch.utils/src/main/java/li/strolch/utils/collections/CollectionsHelper.java new file mode 100644 index 000000000..f646733a6 --- /dev/null +++ b/li.strolch.utils/src/main/java/li/strolch/utils/collections/CollectionsHelper.java @@ -0,0 +1,39 @@ +package li.strolch.utils.collections; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collector; +import java.util.stream.Collectors; + +public class CollectionsHelper { + + public static Collector, T> singletonCollector() { + return singletonCollector(null); + } + + public static Collector, T> singletonCollector(String errorMsg) { + return Collector.of(ArrayList::new, List::add, (left, right) -> { + left.addAll(right); + return left; + }, list -> { + + if (list.isEmpty()) { + if (errorMsg == null) { + throw new IllegalStateException("Expect one element, but received no elements"); + } else + throw new IllegalStateException(errorMsg); + } + + if (list.size() != 1) { + String listS = list.stream().map(Object::toString).collect(Collectors.joining(", ")); + if (errorMsg == null) { + throw new IllegalStateException( + "Expect one element, but received " + list.size() + " in list " + listS); + } else + throw new IllegalStateException(errorMsg + ": " + listS); + } + + return list.get(0); + }); + } +} diff --git a/li.strolch.utils/src/main/java/li/strolch/utils/dbc/DBC.java b/li.strolch.utils/src/main/java/li/strolch/utils/dbc/DBC.java index f78d478df..780d8f51c 100644 --- a/li.strolch.utils/src/main/java/li/strolch/utils/dbc/DBC.java +++ b/li.strolch.utils/src/main/java/li/strolch/utils/dbc/DBC.java @@ -27,7 +27,9 @@ import li.strolch.utils.helper.StringHelper; */ public enum DBC { - PRE, INTERIM, POST; + PRE, + INTERIM, + POST; public void assertEquals(String msg, T value1, T value2) { if (value1 == null && value2 == null) @@ -44,6 +46,18 @@ public enum DBC { throw new DbcException(ex); } + public void assertEqualsIgnoreOrdering(String msg, Collection value1, Collection value2) { + if (value1 == null && value2 == null) + return; + + if (value1 != null && value2 != null && value1.containsAll(value2) && value2.containsAll(value1)) + return; + + String ex = "{0}: {1} != {2}"; //$NON-NLS-1$ + ex = MessageFormat.format(ex, msg, value1, value2); + throw new DbcException(ex); + } + public void assertNotEquals(String msg, T value1, T value2) { if (value1 != null && !value1.equals(value2)) return; @@ -150,7 +164,8 @@ public enum DBC { public void assertExists(String msg, File file) { if (!file.exists()) { - String ex = MessageFormat.format("Illegal situation as file ({0}) does not exist: {1}", file, msg); //$NON-NLS-1$ + String ex = MessageFormat + .format("Illegal situation as file ({0}) does not exist: {1}", file, msg); //$NON-NLS-1$ ex = MessageFormat.format(ex, msg); throw new DbcException(ex); }