From d5dc39e8ff10c72b133bc4f0a79a6b8938cbd9ce Mon Sep 17 00:00:00 2001 From: Joern Muehlencord Date: Sun, 17 Nov 2019 15:08:07 +0100 Subject: [PATCH] introduced StreamUtils --- .../muehlencord/shared/util/StreamUtils.java | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 util/src/main/java/de/muehlencord/shared/util/StreamUtils.java diff --git a/util/src/main/java/de/muehlencord/shared/util/StreamUtils.java b/util/src/main/java/de/muehlencord/shared/util/StreamUtils.java new file mode 100644 index 0000000..07a97fb --- /dev/null +++ b/util/src/main/java/de/muehlencord/shared/util/StreamUtils.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package de.muehlencord.shared.util; + +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collector; +import java.util.stream.Collectors; + +/** + * + * @author Joern Muehlencord (joern@muehlencord.de) + */ +public class StreamUtils { + + public static Collector singletonCollector() { + return getCollectorFunction(getListTSingleFunction()); + } + + private static Collector getCollectorFunction(Function, T> listTFunction) { + return Collectors.collectingAndThen(Collectors.toList(), listTFunction); + } + + private static Function, T> getListTSingleFunction() { + return list -> { + if (list == null) { + throw new IllegalStateException("List must not be null"); + } + if (list.size() != 1) { + throw new IllegalStateException("List contains not exactly one element (size=" + list.size() + ")"); + } + return list.get(0); + }; + } + +}