All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.javers.common.collections.Sets Maven / Gradle / Ivy

There is a newer version: 7.6.1
Show newest version
package org.javers.common.collections;

import org.javers.common.validation.Validate;

import java.util.*;
import java.util.Collections;
import java.util.function.Function;
import java.util.stream.Collector;

import static java.util.Arrays.asList;
import static java.util.Collections.EMPTY_SET;

/**
 * @author Maciej Zasada
 */
public class Sets {

    private Sets() {
    }

    /**
     * null args are allowed
     */
    public static  Set intersection(Set first, Set second) {
        if (first == null || second == null) {
            return EMPTY_SET;
        }

        Set intersection = new HashSet<>();

        for (E e : first) {
            if (second.contains(e)) {
                intersection.add(e);
            }
        }
        return intersection;
    }

    public static  Set xor(Set first, Set second) {
        Set xor = difference(first, second);
        xor.addAll(difference(second, first));

        return xor;
    }

    /**
     * null args are allowed
     */
    public static  Set difference(Set first, Set second) {
        if (first == null) {
            return EMPTY_SET;
        }

        if (second == null) {
            return first;
        }

        Set difference = new HashSet<>(first);
        difference.removeAll(second);
        return difference;
    }

    public static  Set asSet(E... elements) {
        return asSet(asList(elements));
    }

    public static  Set asSet(Collection elements) {
        if (elements == null) {
            return Collections.emptySet();
        }
        return new HashSet<>(elements);
    }

    /**
     * @return ImmutableSet
     */
    public static  Set transform(Set input, Function transformation) {
        Validate.argumentsAreNotNull(input, transformation);
        return input.stream().map(transformation::apply).collect(toImmutableSet());
    }

    private static  Set nullSafe(Set set) {
        if (set == null) {
            return EMPTY_SET;
        }
        return set;
    }

    /**
     * @return index -> value
     */
    public static  Map asMap(Set input) {
        if (input == null){
            return null;
        }

        Map result = new HashMap<>();
        int i = 0;

        for (T element : input) {
            result.put(i, element);
            i++;
        }

        return result;
    }

    public static  Collector, Set> toImmutableSet() {
        return Collector.of(HashSet::new, Set::add, (left, right) -> {
            left.addAll(right);
            return left;
        }, Collections::unmodifiableSet);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy