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

cn.hutool.core.collection.TransCollection Maven / Gradle / Ivy

There is a newer version: 5.8.33
Show newest version
package cn.hutool.core.collection;

import cn.hutool.core.lang.Assert;

import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * 使用给定的转换函数,转换源集合为新类型的集合
 *
 * @param  源元素类型
 * @param  目标元素类型
 * @author looly
 * @since 5.4.3
 */
public class TransCollection extends AbstractCollection {

	private final Collection fromCollection;
	private final Function function;

	/**
	 * 构造
	 *
	 * @param fromCollection 源集合
	 * @param function       转换函数
	 */
	public TransCollection(Collection fromCollection, Function function) {
		this.fromCollection = Assert.notNull(fromCollection);
		this.function = Assert.notNull(function);
	}

	@Override
	public Iterator iterator() {
		return IterUtil.trans(fromCollection.iterator(), function);
	}

	@Override
	public void clear() {
		fromCollection.clear();
	}

	@Override
	public boolean isEmpty() {
		return fromCollection.isEmpty();
	}

	@Override
	public void forEach(Consumer action) {
		Assert.notNull(action);
		fromCollection.forEach((f) -> action.accept(function.apply(f)));
	}

	@Override
	public boolean removeIf(Predicate filter) {
		Assert.notNull(filter);
		return fromCollection.removeIf(element -> filter.test(function.apply(element)));
	}

	@Override
	public Spliterator spliterator() {
		return SpliteratorUtil.trans(fromCollection.spliterator(), function);
	}

	@Override
	public int size() {
		return fromCollection.size();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy