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

io.datakernel.util.CollectionUtils Maven / Gradle / Ivy

package io.datakernel.util;

import io.datakernel.annotation.Nullable;

import java.util.*;
import java.util.stream.Stream;

import static java.util.Arrays.asList;
import static java.util.Collections.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toSet;

public class CollectionUtils {
	private CollectionUtils() {
	}

	public static  List concat(List list1, List list2) {
		List result = new ArrayList<>(list1.size() + list2.size());
		result.addAll(list1);
		result.addAll(list2);
		return result;
	}

	@SafeVarargs
	public static  Set set(T... items) {
		return new LinkedHashSet<>(asList(items));
	}

	public static  Set difference(Set a, Set b) {
		return a.stream().filter(t -> !b.contains(t)).collect(toSet());
	}

	public static  Set intersection(Set a, Set b) {
		return a.size() < b.size() ?
				a.stream().filter(b::contains).collect(toSet()) :
				b.stream().filter(a::contains).collect(toSet());
	}

	public static  boolean hasIntersection(Set a, Set b) {
		return a.size() < b.size() ?
				a.stream().anyMatch(b::contains) :
				b.stream().anyMatch(a::contains);
	}

	public static  Set union(Set a, Set b) {
		return Stream.concat(a.stream(), b.stream()).collect(toSet());
	}

	public static  T first(Iterable iterable) {
		return iterable.iterator().next();
	}

	public static  Set nullToEmpty(@Nullable Set set) {
		return set != null ? set : emptySet();
	}

	public static  List nullToEmpty(@Nullable List list) {
		return list != null ? list : emptyList();
	}

	public static  Map nullToEmpty(@Nullable Map map) {
		return map != null ? map : emptyMap();
	}

	public static  Collection nullToEmpty(@Nullable Collection collection) {
		return collection != null ? collection : emptyList();
	}

	public static  Iterable nullToEmpty(@Nullable Iterable iterable) {
		return iterable != null ? iterable : emptyList();
	}

	public static  Iterator nullToEmpty(@Nullable Iterator iterator) {
		return iterator != null ? iterator : emptyIterator();
	}

	public static  List list() {
		return emptyList();
	}

	@SuppressWarnings("unchecked")
	public static  List list(T... items) {
		return asList(items);
	}

	public static  String toLimitedString(Collection collection, int limit) {
		return collection.stream()
				.limit(limit)
				.map(Object::toString)
				.collect(joining(",", "[", collection.size() <= limit ? "]" : ",..]"));
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy