introduced StreamUtils

This commit is contained in:
2019-11-17 15:08:07 +01:00
parent 233164fb54
commit d5dc39e8ff

View File

@ -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 <T> Collector<T, ?, T> singletonCollector() {
return getCollectorFunction(getListTSingleFunction());
}
private static <T> Collector<T, ?, T> getCollectorFunction(Function<List<T>, T> listTFunction) {
return Collectors.collectingAndThen(Collectors.toList(), listTFunction);
}
private static <T> Function<List<T>, 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);
};
}
}