/* * Copyright (C) 2018-2021 Ignite Realtime Foundation. All rights reserved. * * Licensed 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 org.jivesoftware.util; import javax.annotation.Nonnull; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; /** * A utility class that provides re-usable functionality that relates to Java collections. * * @author Guus der Kinderen, guus.der.kinderen@gmail.com */ public class CollectionUtils { /** * Returns a stateful stream filter that, once applied to a stream, returns a stream consisting * of the distinct elements (according to the specified key). *

* The implementation of {@link Stream#distinct()} can be used to return a stream that has distinct * elements, based on the implementation of {@link Object#equals(Object)}. That implementation does * not allow to filter a stream based on one property of each object. The implementation of provided * by this method does. * * @param keyExtractor A function to extract the desired key from the stream objects (cannot be null). * @param Stream element type. * @return A filter * @see Stack Overflow: Java Lambda Stream Distinct() on arbitrary key? */ public static Predicate distinctByKey( Function keyExtractor ) { final Map seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent( keyExtractor.apply( t ), Boolean.TRUE ) == null; } /** * Returns all elements that occur more than exactly once in the combination of all elements from all provided * collections. * * @param collections The collection for which to return duplicates * @param The type of the entities in the collections. * @return The duplicates */ @Nonnull public static Set findDuplicates(@Nonnull final Collection... collections) { final Set merged = new HashSet<>(); final Set duplicates = new HashSet<>(); for (Collection collection : collections) { for (V o : collection) { if (!merged.add(o)) { duplicates.add(o); } } } return duplicates; } }