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

org.jhotdraw8.collection.mapped.MappedSet Maven / Gradle / Ivy

The newest version!
/*
 * @(#)MappedSet.java
 * Copyright © 2023 The authors and contributors of JHotDraw. MIT License.
 */
package org.jhotdraw8.collection.mapped;

import org.jspecify.annotations.Nullable;

import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * Maps a {@link Set} to a different element type.
 * 

* The underlying Set is referenced - not copied. * * @param the mapped element type * @param the original element type * @author Werner Randelshofer */ public final class MappedSet extends AbstractSet { private final Set backingSet; private final Function mapf; public MappedSet(Set backingSet, Function mapf) { this.backingSet = backingSet; this.mapf = mapf; } @Override public boolean contains(Object o) { // FIXME Should throw UnsupportedOperationException! return backingSet.contains(o); } @Override public Iterator iterator() { return new Iterator<>() { private final Iterator i = backingSet.iterator(); @Override public boolean hasNext() { return i.hasNext(); } @Override public E next() { return mapf.apply(i.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public Spliterator spliterator() { class MappingSpliterator implements Spliterator { private final Spliterator i; public MappingSpliterator(Spliterator i) { this.i = i; } @Override public boolean tryAdvance(Consumer action) { return i.tryAdvance(f -> action.accept(mapf.apply(f))); } @Override public @Nullable Spliterator trySplit() { Spliterator fSpliterator = i.trySplit(); return fSpliterator == null ? null : new MappingSpliterator(fSpliterator); } @Override public long estimateSize() { return i.estimateSize(); } @Override public int characteristics() { return i.characteristics(); } } return new MappingSpliterator(backingSet.spliterator()); } @Override public int size() { return backingSet.size(); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy