[New] Added CollectionsHelper.singletonCollector()

This commit is contained in:
Robert von Burg 2017-10-12 16:14:21 +02:00
parent 7dd6aa8afc
commit abd5dc18e0
2 changed files with 56 additions and 2 deletions

View File

@ -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 <T> Collector<T, List<T>, T> singletonCollector() {
return singletonCollector(null);
}
public static <T> Collector<T, List<T>, 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);
});
}
}

View File

@ -27,7 +27,9 @@ import li.strolch.utils.helper.StringHelper;
*/
public enum DBC {
PRE, INTERIM, POST;
PRE,
INTERIM,
POST;
public <T> 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 <T> void assertEqualsIgnoreOrdering(String msg, Collection<T> value1, Collection<T> 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 <T> 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);
}