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

ru.progrm_jarvis.javacommons.collection.Iterables Maven / Gradle / Ivy

package ru.progrm_jarvis.javacommons.collection;

import lombok.experimental.UtilityClass;
import lombok.val;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Unmodifiable;

import java.util.*;

/**
 * Utilities related to {@link Iterable} iterables.
 */
@UtilityClass
public class Iterables {

    /**
     * Converts the given iterable into unmodifiable {@link List}.
     *
     * @param iterable iterable to be converted
     * @param  type of the elements
     * @return creates unmodifiable list
     */
    public  @NotNull @Unmodifiable List toList(final @NotNull Iterable iterable) {
        final Iterator iterator;
        if (!(iterator = iterable.iterator()).hasNext()) return Collections.emptyList();

        val list = new ArrayList();
        do list.add(iterator.next());
        while (iterator.hasNext());

        return Collections.unmodifiableList(list);
    }

    /**
     * Converts the given iterable into modifiable {@link List}.
     *
     * @param iterable iterable to be converted
     * @param  type of the elements
     * @return creates modifiable list
     */
    public  @NotNull List toModifiableList(final @NotNull Iterable iterable) {
        final Iterator iterator;
        if (!(iterator = iterable.iterator()).hasNext()) return new ArrayList<>(0);

        val list = new ArrayList();
        do list.add(iterator.next());
        while (iterator.hasNext());

        return list;
    }

    /**
     * Converts the given iterable into unmodifiable {@link Set}.
     *
     * @param iterable iterable to be converted
     * @param  type of the elements
     * @return creates unmodifiable set
     */
    public  @NotNull @Unmodifiable Set toSet(final @NotNull Iterable iterable) {
        final Iterator iterator;
        if (!(iterator = iterable.iterator()).hasNext()) return Collections.emptySet();

        val set = new HashSet();
        do set.add(iterator.next());
        while (iterator.hasNext());

        return Collections.unmodifiableSet(set);
    }

    /**
     * Converts the given iterable into unmodifiable {@link Set}.
     *
     * @param iterable iterable to be converted
     * @param  type of the elements
     * @return creates unmodifiable set
     */
    public  @NotNull Set toModifiableSet(final @NotNull Iterable iterable) {
        final Iterator iterator;
        if (!(iterator = iterable.iterator()).hasNext()) return new HashSet<>(0);

        val set = new HashSet();
        do set.add(iterator.next());
        while (iterator.hasNext());

        return Collections.unmodifiableSet(set);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy