org.jhotdraw8.collection.mapped.MappedList Maven / Gradle / Ivy
Show all versions of org.jhotdraw8.collection Show documentation
/*
* @(#)MappedList.java
* Copyright © 2023 The authors and contributors of JHotDraw. MIT License.
*/
package org.jhotdraw8.collection.mapped;
import org.jspecify.annotations.Nullable;
import java.util.AbstractList;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* Maps a {@link List} to a different element type.
*
* The underlying list is referenced - not copied.
*
* @param the mapped element type
* @param the original element type
* @author Werner Randelshofer
*/
public final class MappedList extends AbstractList {
private final List backingList;
private final Function mapf;
public MappedList(List backingList, Function mapf) {
this.backingList = backingList;
this.mapf = mapf;
}
@Override
public boolean contains(Object o) {
return backingList.contains(o);
}
@Override
public E get(int index) {
return mapf.apply(backingList.get(index));
}
@Override
public Iterator iterator() {
return new Iterator<>() {
private final Iterator i = backingList.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 super E> 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(backingList.spliterator());
}
@Override
public int size() {
return backingList.size();
}
@Override
public List subList(int fromIndex, int toIndex) {
return new MappedList<>(backingList.subList(fromIndex, toIndex), mapf);
}
}